Java中的ArrayList程序

3
System.out.println("Enter the appointment ID to see the full details :");
int y=in.nextInt();
int r;
for(r=0;r<count;r++)
{
    if(all.get(r).getID()==y)
    {
         all.get(r).display();
    }
}

我正在使用这段代码通过get语句检索已输入的完整详细信息并进行显示。这是我的程序的一小部分。我想知道是否有其他方法来实现它。

2个回答

4
更好的方法是使用一个HashMap<Integer,DetailsClass>而不是一个ArrayList。

然后,您只需要编写:

HashMap<Integer,DetailsClass> map = new HashMap<>();

...

if (map.containsKey(y)) {
    DetailsClass details = map.get(y);
    details.display();
}

这使得代码更加简单和高效,因为在HashMap中搜索一个键只需要期望的常数时间,而在List中搜索则需要线性时间。

如果你必须使用一个ArrayList,至少在找到你要查找的对象后立即退出循环:

int y=in.nextInt();
for(int r=0;r<count;r++)
{
    if(all.get(r).getID()==y)
    {
         all.get(r).display();
         return; // or break; depending on where this for loop is located
    }
}

我需要使用ArrayList(这是必须的)。想知道是否有其他检索数据的方法,而不是以上所有.get(r).display(); - ranjit kumar
@ranjitkumar 如果是这样的话,你别无选择,只能遍历ArrayList。使用Java 8流可以更简洁地编写代码,但如果不允许使用HashMap,我也不会使用Streams。 - Eran
通常认为,先调用containsKey再调用get是不良实践。 - Boris the Spider
有没有改变的余地(可以让我更多地使用 get)? - ranjit kumar
@BoristheSpider 我同意可以用单个 get() 调用来替换它,但在这样一个简单的程序中,我不认为优化有什么意义。无论如何,OP都不能使用 HashMap,所以这并不重要。 - Eran

2

永远不要通过索引循环遍历List。您不知道List的内部实现,循环可能导致O(n^2)的复杂度。

我建议采用以下方式:

System.out.println("Enter the appointment ID to see the full details :");
final int y = in.nextInt();
for(final Thing thing : all) {
    if(thing.getID() == y) {
         thing.display();
    }
}

或者,如果您可以使用Java 8,则:

all.stream()
        .filter(t -> t.getID() == y)
        .findFirst()
        .ifPresent(Thing::display);

1
据我所知,这是一种糟糕的习惯,值得改掉。 - Boris the Spider
我想尝试以下代码:System.out.println("输入约会ID以查看完整详情:"); final int y = in.nextInt(); for(final Thing thing : all) { if(thing.getID() == y) { thing.display(); } } 但是我不确定 (final Thing thing : all) 这个语句的作用(请不要生气,我是Java新手)。 - ranjit kumar
有人能帮我理解Boris the Spider建议的代码的工作方式吗? - ranjit kumar
@BoristheSpider 这不是很标准(在方法范围内),除了对你的编码偏好发表声明之外,它并没有为答案增加任何东西。 - shmosel
1
@shmosel 我不同意,但你当然有权发表自己的观点。我会认为我们所写的每一行代码都反映了我们的编码偏好。花括号的位置、变量的命名、空格的使用等等,每一个细节都是如此。 - Boris the Spider
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接