gpt4 book ai didi

java - 在字典程序中比较对象与ArrayList

转载 作者:行者123 更新时间:2023-12-01 11:03:20 28 4
gpt4 key购买 nike

import java.io.*;
import java.util.*;

public class Dictionary
{
protected static int line_number = 0;

public static void main(String[] args)
{
List<Dict> my_collection = new ArrayList<Dict>();
List<Dict> search_term = new ArrayList<Dict>();
File filename = new File("dict.txt");

try
{
Scanner data_store = new Scanner(filename);
Scanner keyboard = new Scanner(System.in);

while(data_store.hasNextLine())
{
String word = data_store.nextLine();
Dict m = new Dict(word);
my_collection.add(m);
line_number++;
}

System.out.println(my_collection.size() + " words were loaded.");
System.out.println("What word are you looking for?");
String find_word = keyboard.nextLine();
while(!(find_word.equals("no")))
{
Dict n = new Dict(find_word);
for(line_number = 0; line_number < my_collection.size(); line_number++)
{
if(my_collection.get(line_number).equals(n))
{
System.out.println("\"" + find_word + "\" is at index " + line_number);
}
}
System.out.println("Search again?");
find_word = keyboard.nextLine();
}
}

catch(FileNotFoundException e)
{
System.out.println("Nope!");
}
}
}

我正在尝试浏览一个 Dictionary.txt 文件(此处称为 dict.txt),将其放入 ArrayList 中(这似乎可行)并允许输入输出该单词在 ArrayList 中的位置。我尝试通过将 user_input 转换为 ArrayList 组成的对象来实现此目的,但我无法比较两者,以便我可以输出 ArrayList 中对象的正确实例。请帮忙!

最佳答案

什么是Dict...如果是你自定义的类,那么让这个类实现Comparable Interface。

class Dict implements Comparable<Dict>
{
@Override
public int compareTo(Dict other)
{
//here you can call "compareTo on Strings or equals on String
}
}


使用 Comparable 接口(interface)具有优势,因为现在我们可以在 Dict 上调用各种 Arrays 实用程序类方法。

或者作为一种更简单的方法,只需重写 Dict 类中的 equals 方法即可。但是,您还需要重写 hashCode 方法,这样 hashCodeequals 之间的契约始终保持不变。

关于java - 在字典程序中比较对象与ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33163357/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com