如何在初始化一次后将新对象添加到对象类型数组?

时间:2015-02-17 17:11:10

标签: java arrays object

我需要在以下数组中添加更多元素(在本例中为边缘)。我该怎么做?我需要一个快速的解决方案,因为没有时间来改变架构。有可能吗?我尝试将所有内容从此数组复制到ArrayList。但我陷入了对象类型不匹配的困境。

这是我的Dijkstra类,其中包含主要方法:

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;


public class Dijkstra {
public static Graph graphMappingTemp;
public static ArrayList<Edge> arrayListEdge;


public static Edge[] GRAPH = {
  new Edge("Sri Lanka", "UK", 46),
  new Edge("Sri Lanka", "USA", 65),
  new Edge("Sri Lanka", "Dubai", 20),
  new Edge("Sri Lanka", "Singapore", 20),
  new Edge("Sri Lanka", "Malaysia", 35),
  new Edge("USA", "UK", 35),
  new Edge("UK", "USA", 35),
  new Edge("UK", "Dubai", 26),
  new Edge("Dubai", "Sri Lanka", 20),
  new Edge("Singapore", "Sri Lanka", 20),
  new Edge("Singapore", "Malaysia", 35),
  new Edge("Singapore", "Australia", 110),
  new Edge("Malaysia", "New Zealand", 73),
  new Edge("New Zealand", "Singapore", 113),
  new Edge("New Zealand", "Australia", 43),
  new Edge("Australia", "Dubai", 150),};

public static Graph graphMapping = new Graph(GRAPH);


private static final String START = "UK";
private static final String END = "USA";

public static void main(String[] args) {
    //graphMappingTemp = new Graph(GRAPH); //Create a new Graph
    //arrayListEdge = new ArrayList<Edge>(); //Create a new array list

    for (Edge edge : GRAPH) {
        arrayListEdge.add(edge); //copy all edges from Graph to ArrayList
    }

    //graphMapping = new Graph(arrayListEdge); //Create a new graph with the ArrayList

    Scanner input = new Scanner(System.in);


    graphMapping.runDijkstrasAlgo(START);
    graphMapping.printLeastCostPath(END);

    addCountry(input);
    graphMapping.printAllPaths();



    /*removeCountry(input);
    graphMapping.printAllPaths();*/

    //arrayListEdge.add(new Edge("UK", "USA", 56));         //test code

    input.close();
}

//Search least cost path option
public void searchLCP(Scanner input) {
    System.out.println("Please Enter the Origin : ");
    String inputOrigin = input.next();

    System.out.println("Please Enter the Destination : ");
    String inputDestination = input.next();
    //printLeastCostPath(inputDestination);
}

//Add country option
public static void addCountry(Scanner input){
    System.out.println("Please Enter your Country : ");
    String country = input.next();
    graphMapping.graph.put(country, new Vertex(country));

    //System.out.println(graphMapping.graph.containsKey("PAK"));

    System.out.println("Country successfully added!");

}

//Remove Country option
public static void removeCountry(Scanner input){
    System.out.println("Please Enter your Country : ");
    String country = input.next();
    System.out.println(country);
    graphMapping.graph.remove(country);

    System.out.println("Country successfully removed!");
}

}

边缘类:

public class Edge {
public final String country1, country2;
public final int distance;

public Edge(String country1, String country2,int distance) {
    this.country1 = country1;
    this.country2 = country2;
    this.distance = distance;
}

}

图表类:

import java.util.HashMap;
import java.util.Map;
import java.util.NavigableSet;
import java.util.TreeSet;


public class Graph {
public final Map<String, Vertex> graph;

public Graph(Edge[] edges) {

    graph = new HashMap<>(edges.length);

    for (Edge e : edges) {
        if (!graph.containsKey(e.country1)){
            graph.put(e.country1, new Vertex(e.country1));
        }

        if (!graph.containsKey(e.country2)){
            graph.put(e.country2, new Vertex(e.country2));
        }
    }

    for (Edge e : edges) {
        graph.get(e.country1).neighbours.put(graph.get(e.country2),                          e.distance); // Since it is an directed graph
    }
}

public void runDijkstrasAlgo(String origin) {
    if(!graph.containsKey(origin)){
        System.err.printf("No starting vertex to be found \"%s\"\n", origin);
    }

    final Vertex source = graph.get(origin);
    NavigableSet<Vertex> q = new TreeSet<>();

    for (Vertex v : graph.values()) {
        v.previous = v == source ? source : null;
        v.distance = v == source ? 0 : Integer.MAX_VALUE;
        q.add(v);
    }

    runDijkstrasAlgo(q);
}

private void runDijkstrasAlgo(final NavigableSet<Vertex> q) {
    Vertex u,v;

    while (!q.isEmpty()) {
        u = q.pollFirst();
        if (u.distance == Integer.MAX_VALUE) {
            break;
        }

        for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) {
            v = a.getKey();

            final int alternateDistance = u.distance + a.getValue();

            if (alternateDistance < v.distance) { // shorter path to neighbour found
                q.remove(v);
                v.distance = alternateDistance;
                v.previous = u;
                q.add(v);
            }
        }
    }
}

 /** Prints a path from the source to the specified vertex */
   public void printLeastCostPath(String destination) {
      if (!graph.containsKey(destination)) {
         System.err.printf("No end vertex to be found \"%s\"\n", destination);
         return;
      }

      graph.get(destination).printLeastCostPath();
      System.out.println();
   }

   public void printAllPaths() {
       for (Vertex v : graph.values()) {
        v.printLeastCostPath();
        System.out.println();
    }
}

}

1 个答案:

答案 0 :(得分:1)

如果您明确地定义了数组,则无法向数组中添加更多元素。如果要拥有可以展开的数组,可以使用ArrayList。你能告诉我们它给出了什么错误以及在哪里?

更新:在您构建阵列时,请将其保留为ArrayList。然后,当您准备好将其转换为数组时(即,当您完成增长时),您可以

Edge[] convertedArray = new Edge[thatArrayList.size()];
convertedArray = thatArrayList.toArray(convertedArray );