比较同一List Java中的元素 [英] Comparing elements in the same List Java

查看:447
本文介绍了比较同一List Java中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较同一List (The List "list)中的元素,如果它们在同一行中打印出来,则我是编程新手,我还没有完全理解列表数组以及使用它们的时间.

I want to compare the elements in the same List (The List "list) and if they are the same print out a line, I'm fairly new to programming and I dont yet completely understand the difference between List and an array and when you use them.

有人建议使用下面的代码,尽管该代码没有打印出任何内容.由于数组中有两对,所以我希望至少打印一次.任何帮助将不胜感激,谢谢!

Someone kindly suggested the code below and although it compliles nothing is being printed out. Since there are two pairs in my array I would expect something to print out at least once. Any help would be most appreciated thanks!

                        List<Double> list = new ArrayList<Double>();

                        while (search.find()){ 
                            list.add(Double.parseDouble(search.group(1)));
                        }


                        for(int i= 0 ; i < list.size()-1; i++){
                            //System.out.println(list.get(i));  // Successfully prints out all doubles in the SHADING:BUILDING:DETAILED class
                            for(int k = i+1 ; k < list.size() ; k++){
                                if(list.get(i) == list.get(k)){
                                    System.out.println(i + "and" + k + "are pairs");
                                }
                            }
                        }           
                    }
                }

推荐答案

比较的编码方式会重复.此外,恐怕这不是访问列表中元素的正确方法.

The way you have coded the comparation repeats itself. Besides, that is not the correct way you access an element in a list, I'm afraid.

例如,假设您有i = 0(例如值2.0)和k = 2(值5.2),但是后来您有i = 2(5.2)和k = 0(2.0),即相同的.我建议您采取以下措施,避免重复.

For example, lets say you have the i = 0 (value 2.0 for example) and k = 2 (value 5.2), but later you have i = 2 (5.2) and k = 0 (2.0), which is the same. I suggest you the following, which avoids this repetition.

for (int i = 0; i < list.size()-1; i++) 
   for (int k = i+1; k < list.size(); k++) 
      if(list.get(i) == list.get(k))
         System.out.println(i + " and "+ k +" are pairs");

当然,您必须确保列表的大小大于1,否则它将引发OutOfBoundsException. 希望这对您有帮助^^

Of course, you have to make sure that the list's size is bigger than 1, otherwise it will throw OutOfBoundsException. Hope this helps ^^

编辑#2 如果它包含一个空安全的等于,请尝试使用以下内容:

EDIT #2 Try and use the following if, it contains a null-safe equals:

if(Objects.equals(list.get(i), list.get(k)))

这篇关于比较同一List Java中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆