【发布时间】:2019-03-30 14:34:02
【问题描述】:
我正在尝试创建邻接列表。问题是我的实现在内存中花费了很多......
我读了一个单词文件,将它们添加到我的图表中并添加图表的邻居
static public void createEdges(){
for(String string : words){ //words is the list of all the ~4 000 words that have been read
ArrayList<String> wordlist = new ArrayList<String>();
// ........................................................
//(irrelevant part where I create a new String "word" from "string")
// .........................................................
if (Contains(word) != null){ //Contains checks if the new String "word" is a part of the file I read.
wordlist.add(word);
}
list.put(string, wordlist); //list is of type: Hashtable<String, ArrayList<String>>; and represents the wordgraph where "string" is the node and "wordlist" is the neighbors of the node
}}
我认为节省内存的一种方法是不创建一个新的 ArrayList evere 循环,因为它会循环约 4 000 次......但是我想不出任何好的方法来存储我的相邻节点。使用这种数据结构是否注定要达到我的目的,还是有更聪明的方法来实现它?
【问题讨论】:
-
这段代码有点混乱。变量“list”、对象“Contains”和变量“word”没有上下文。没有更多的上下文,将很难提供帮助。另外,你怎么知道这会消耗太多的内存?你想达到什么目的?
-
@aglassman 是的,我现在明白了,谢谢。 Contains 是一种简单检查我读取的文件是否包含新字符串“单词”的方法。列出邻接列表,因此列表中的变量“string”是节点,变量“wordlist”是邻居的 ArrayList。我正在制作一个 BFS,以找到从一个词到另一个词的方式。我想实现一个尽可能快地支持这种搜索但又不存储太多数据的数据结构,我觉得这样做是因为它创建了大量的 ArrayLists...
-
有趣的问题,但我不明白你将列表放入地图的部分。由于您正在为每个 for 循环迭代创建一个新的 ArrayList,所以 Hashtable 中的每个条目不会是一个条目吗?
标签: java arraylist graph-theory adjacency-list