나는 파일이 있다고 말함으로써 시작하겠습니다. 자세한 내용은 here을 확인하십시오.HashMap Java에서 여러 값을 표시 할 수 없음
이미 여러 값으로 해시 맵의 가장자리를 추가했습니다. 이 코드를 추가하여 확인해 보겠습니다.
map.put(nodes.get(i), edges);
System.out.println(nodes.get(i) + " " + map.get(nodes.get(i)));
지도에 각 항목을 추가 한 후 성공적으로 추가되었는지 확인합니다. 예, 효과가있었습니다.
a0 [[email protected]]
a1 [[email protected], [email protected], [email protected]]
a2 [[email protected], [email protected], [email protected]]
a3 [[email protected], [email protected], [email protected]]
그러나지도의 내용을 표시하기 위해 다른 방법을 만들 때, 나는지도가 비어 있음을 발견 :
여기에 출력합니다. 이것에 대한
a0 []
a1 []
a2 []
a3 []
무엇 될 수있는 가능한 이유 :
public void viewFile() {
for(int i=0; i<nodes.size();i++) {
System.out.println(nodes.get(i) + " " + this.map.get(nodes.get(i)));
}
}
위의 코드의 출력은 이것이다 : 여기 코드는? 왜 이런 일이 일어 났는지 나는 혼란 스럽다. 여기
class Reader {
HashMap<String, Vertex> vertexList;
Map<String, ArrayList<Edge>> map;
ArrayList<String> nodes;
ArrayList<Edge> edges;
public Reader(String fileName) {
vertexList = new HashMap<String, Vertex>();
map = new HashMap<String, ArrayList<Edge>>();
nodes = new ArrayList<String>();
edges = new ArrayList<Edge>();
readFile(fileName);
}
private void readFile(String fileName) {
try{
FileReader file = new FileReader(fileName);
Scanner sc = new Scanner(file);
int i = 0;
while (sc.hasNextLine()) {
input.add(sc.nextLine());
i++;
}
setNodes();
setVertices();
System.out.println();
file.close();
} catch(Exception e){
System.out.println(e);
}
}
public void setNodes() {
System.out.println();
for(int i=0; i<input.size(); i++) {
line = this.input.get(i);
nodes.add(line.substring(0,line.indexOf("-")).trim());
adjLine.add(line.substring(line.indexOf("-")+1).trim());
}
}
private void setVertices() {
String[] listEdges;
for(int i=0; i<nodes.size(); i++) {
//if vertex does not exist, create it
if(vertexList.containsKey(nodes.get(i))) {
vertexList.put(nodes.get(i), new Vertex(nodes.get(i)));
}
line = adjLine.get(i);
//separate adj edges to *
if(line.contains("*")) {
listEdges = line.split("\\*");
} else {
listEdges = new String[1];
listEdges[0] = line;
}
//add edges to specified vertex
for(int j=0; j < listEdges.length; j++) {
String[] word = listEdges[j].split(",");
edges.add(new Edge(vertexList.get(word[0]),Double.parseDouble(word[1])));
}
map.put(nodes.get(i), edges);
System.out.println(nodes.get(i) + " " + map.get(nodes.get(i)));
edges.clear();
}
}
우리는 더 볼 필요가 당신의 코드, 특히지도를 작성하는 코드 – NPE
@princepiero 어떻게 그리고 어디에서 viewFile() 메서드를 호출합니까? – Lakshmi
안녕하세요 @NPE 나는 질문을 편집했다. :) – princepiero