冒泡排序Java中的对象数组 [英] Bubble sorting an object array in Java

查看:145
本文介绍了冒泡排序Java中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么排序对​​象的数组?这是我的code排序的数组,我收到一个未声明错误:电影TEMP =电影[B]我该怎么申报临时变量,如果它是拿电影的精确值/参考[B]。它可以是任何一种是在同一阵列中三种不同的对象类型?我是新来编程,所以我很抱歉,如果我似乎是无知的;请随时指正或提问,如果我措辞问题不正确。

 公共静态字符串冒泡(动画[]电影){
    对于(INT A = 1; A< movies.length; A ++){
        对于(INT B = 0; B< movies.length - A; B ++){
            如果(((电影并[b] .getTitle())的compareTo((电影并[b + 1] .getTitle())))方式> 0)
                //交换电影[B]与电影[B + 1]
                电影TEMP =电影[B]
            电影并[b] =电影并[b + 1];
            电影[B + 1] =温度;
        }
    }
}


解决方案

当一个数组被定义为电影[] 只能包含类型的对象电影。所以,你只能有电影在里面。然而,为了使这个一般情况下,你应该定义对象的类型和数组对象[]

然而,在code,你是假设你是因为你使用的是确实有电影对象 Movie.getTitle( )。您将无法访问,从对象的引用。我会建议让你的对象实施可比键,使用类型可比作为阵列的类型和你的临时变量。

how do I sort an array of objects? this is my code for sorting the array, I receive a "not a statement" error for: Movie temp = movies[b]; what do i declare the temp variable as if it is to hold the exact value/reference of movies[b]; which could be any of three different object types which are in the same array? I am new to programming so I apologize if i seem to be ignorant; please feel free to correct me or ask questions if I phrased the questions incorrectly.

public static String bubbleSort(Movie[] movies) {
    for (int a=1; a<movies.length; a++) {
        for(int b=0; b<movies.length - a; b++) {
            if (((movies[b].getTitle()).compareTo((movies[b+1].getTitle()))) > 0)
                //swap movies[b] with movies[b+1]
                Movie temp = movies[b];
            movies[b] = movies[b+1];
            movies[b+1] = temp;
        }
    }
}

解决方案

When an array is defined as Movie[] it can only contains objects of type Movie. So you can only have Movies in there. However, to make this general, you should define the type as Object and the array as Object[].

However, in your code, you are assuming that you really do have Movie objects because you're using Movie.getTitle(). You will not be able to access that from references of Object. I would recommend having your objects implement Comparable and using the type Comparable as the type of the array and your temporary variable.

这篇关于冒泡排序Java中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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