简体   繁体   English

如何比较Arraylist中的两个数字?

[英]How to compare two numbers in Arraylist?

I want to compare two numbers in arraylist,but I failed,anyone can help me,here is my code.我想比较arraylist中的两个数字,但我失败了,任何人都可以帮助我,这是我的代码。

MainActivity{
ArrayList<User> users=new ArrayList<User>();
            users.clear();
            int imgid;
            int number=0;
            User use1;
            List<User> user=DataSupport.findAll(User.class);
            for (User use:user){
                use1=new User();
                use1.setNeednumber(use.getNeednumber());
                use1.setMaterialid(use.getMaterialid());
                users.add(use1);
            }
for(int i=1;i<users.size();i++){
                if(users.get(i-1).getMaterialid()==users.get(i).getMaterialid()){

number=number+users.get(i-1).getNeednumber();
                    Log.d("number",""+number);
                }
            }

On the whole,it's like this,I use Litepal to create an database,the database have a table called "User",the table have two column one is "Materialid" one is "Neednumber",I want read the data what I storage in this table and if the "Materialid" is equal let them add.I use above method but it didn't work,the number always zero.who can help me deal with this problem ,thank you very much.总的来说,是这样的,我用Litepal创建了一个数据库,数据库有一个名为“User”的表,该表有两列,一列是“Materialid”,一列是“Neednumber”,我想读取我存储的数据在这个表中,如果“Materialid”相等,让他们添加。我使用上述方法但它不起作用,数字始终为零。谁能帮我解决这个问题,非常感谢。

try this logic试试这个逻辑

    Integer numberArray[] = { 1, 2, 45, 6, 7, 7, 8, 9, 10, 11, 10, 9, 1 };
    Set<Integer> printed = new HashSet<>();
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer s : Arrays.asList(numberArray)) {
        if (printed.add(s)) // Set.add() also tells if the element was in
                            // the Set!
            System.out
                    .println("element: " + s + ", count: " + Collections.frequency(Arrays.asList(numberArray), s));

        if (Collections.frequency(Arrays.asList(numberArray), s) > 1) {
            map.put(s, Collections.frequency(Arrays.asList(numberArray), s));
        }
    }
    Integer sum = 0;
    for (Map.Entry m : map.entrySet()) {
        System.out.println(m.getKey() + " " + m.getValue());
        sum = sum + ((Integer) m.getKey() * (Integer) m.getValue());
    }
    System.out.println("sum is" + sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM