Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 比较对象:使用增强的for循环_Java_Arrays_Object_Foreach_Compare - Fatal编程技术网

Java 比较对象:使用增强的for循环

Java 比较对象:使用增强的for循环,java,arrays,object,foreach,compare,Java,Arrays,Object,Foreach,Compare,我正在遍历一系列对象(不同的网站类型)。但我希望能够显示哪个网站拥有最多的会员。最初,我的代码显示每个网站的成员数量,但我的代码并不完整,因为我不知道如何比较这些对象,以确定哪些对象的成员数量最高。当前代码: public static void mostUsers(){ for (Website w: websiteTypes){ // check if the array index is not null if (w!=nu

我正在遍历一系列对象(不同的网站类型)。但我希望能够显示哪个网站拥有最多的会员。最初,我的代码显示每个网站的成员数量,但我的代码并不完整,因为我不知道如何比较这些对象,以确定哪些对象的成员数量最高。当前代码:

public static void mostUsers(){

        for (Website w: websiteTypes){
            // check if the array index is not null
            if (w!=null){

                System.out.println(w.getType() + "has:" + w.getMembers());
                System.out.println(); // line break

                **//Code to compare amount of users on each site and display highest**
            } else {

                // no more records so quit loop
                break;
            }
        }
    }
使用,或让网站扩展


然后,使用
sort
对网站集进行排序。浏览量最多的网站将出现在您的收藏开始处。

您需要在迭代时跟踪最大用户数

  • 在循环之前,将名为
    maxWebsite
    的变量初始化为
    null
  • 在循环之前,将名为
    max
    的整数初始化为
    integer.MIN\u VALUE
  • 迭代时,测试
    w.getMaxUsers()
    是否优于
    max
  • 如果是,则相应地更新
    maxWebsite
    max
    变量
  • 注意:如果删除循环中的else语句,则必须迭代数组的所有元素。
    如果您使用的是
    集合
    ,使用自定义比较器可能很简单:

    List<Website> l = .......
    l.removeAll(Collections.singleton(null)); //remove null elements from the list
    Website maxWebsite = Collections.max(l, new Comparator<Website>(){
        @Override
        public int compare(Website arg0, Website arg1) {
            return Integer.compare(arg0.getMaxUsers(), arg1.getMaxUsers());
        }           
    });
    
    列表l=。。。。。。。
    l、 removeAll(Collections.singleton(null))//从列表中删除空元素
    Website maxWebsite=Collections.max(l,新的比较器(){
    @凌驾
    公共整数比较(网站arg0、网站arg1){
    返回整数.compare(arg0.getMaxUsers(),arg1.getMaxUsers());
    }           
    });
    
    您使用的集合是否允许空值,因为我会在那里抛出整个if/else。您似乎误解了foreach循环的工作原理。我认为这意味着如果下一个空格为null,则停止遍历数组?这是个坏主意,使用集合,而不是数组。你对Java很陌生,不是吗?这个课程的目的是什么,学校作业?是的,它是为了大学,我只是想能够比较不同班级的属性,但不知道如何去做!