简体   繁体   English

可比的Java

[英]Comparable Java

I have a homework assignment and am having a little bit of trouble. 我有一项家庭作业,遇到一些麻烦。 First the assignment is to make a bar graph of various sizes then adjust and sort them with each click of a button. 首先,任务是制作各种尺寸的条形图,然后单击按钮即可对其进行调整和排序。 I implemented action listener on the main class then made a secondary class to implement comparable. 我在主类上实现了动作侦听器,然后使第二类实现了可比性。 I have an issue calling the comparable function. 我在调用可比功能时遇到问题。 It says my array int[] cant be resolved in a comparable method thats looking for comparable[] Any help or tips would be gratly appreciated. 它说我的数组int []无法以可比的方法来解析,那就是寻找可比的[]任何帮助或技巧都将不胜感激。 Here is my code: 这是我的代码:

import java.util.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

 import javax.swing.*;



 public class TwoSorts extends Applet implements ActionListener

 {
private final int APPLET_WIDTH = 600;
private final int APPLET_HEIGHT = 600;
Button sort;
Label sort_label;
String pr_name;
int[] random = new int[20];
int[] sorter = new int[20];


public void init()

{

    sort = new Button("Sort");
    add(sort);
    sort.addActionListener(this);
    sort_label = new Label("Orange Selection / Black Bubble");
    add(sort_label);
    randomGen(random);
    sorter = random; 
    setBackground (Color.white);
    setSize (APPLET_WIDTH, APPLET_HEIGHT); 
}  

private void randomGen (int...random) {


    for (int i = 0; i < 20; i++){
        random [i] = (int) (20 +(Math.random()*300-20));
        }
}

public void paint(Graphics g)
{
    for (int i = 0; i < 20; i++ ){


        g.setColor(Color.blue);
        g.fillRect((int) (10 + (i*50)), 300, 50, ((random[i])));
        g.setColor(Color.black);
        g.fillRect((int) (10 + (i*50)), 300, 25, (sorter[i]));
    }

    g.drawRect (20, 30, 130, 50);
  sort.setLocation(0,220);
  sort_label.setLocation(0,270);
  sort_label.setSize(400,30);
}


class action extends TwoSorts implements Comparable {


public void actionPerformed(ActionEvent arg0) {


    selectionSort(random);
    insertionSort (sort);
    repaint;

public static void selectionSort (Comparable[] random)  {

    int min;
    Comparable temp;

    for (int index = 0; index < random.length-1; index++)
    {
        min = index;
        for (int scan = index+1; scan < random.length; scan++)
            if (random[scan].compareTo(random[min]) < 0)
                min = scan;

        temp = random[min];
        random[min] = random[index];
        random[index] = temp;
    }

public static void insertionSort (Comparable[] sorter)  {

    for (int index = 1; index < sorter.length; index ++){
        Comparable key = sorter[index];
        int position = index;
        while (position > 0 && key.compareTo(sorter[position-1]) < 0){
            sorter [position] = sorter[position-1];
            position--;
        }

        sorter[position] = key;
    }
}

@Override
public int compareTo(Object o) {
    // TODO Auto-generated method stub
    return 0;
    }
}


@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

Comparable should be implemented by classes with which you might have some reason to compare with other objects of the same type. Comparable应该由您可能有理由与同类型的其他对象进行比较的类来实现。

So for instance, If you have a bar graph of rectangles that need to be sorted you might make a class of rectangles which contains the height, width and position of the rectangle. 因此,例如,如果您有一个需要排序的矩形条形图,则可以制作一个矩形类,其中包含矩形的高度,宽度和位置。 now since this is a class you made up you will need to implement the compareTo function to evaluate which Rectangle is greater or less than another rectangle. 现在,由于这是您组成的一个类,您将需要实现compareTo函数以评估哪个Rectangle大于或小于另一个矩形。

If you look at the compareTo() specification http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Comparable.html you will see: 如果您查看compareTo()规范http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Comparable.html ,则会看到:

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 返回:负整数,零或正整数,因为此对象小于,等于或大于指定的对象。

so if this object is less than the object passed to compareTo() return - , if equal 0, and + if greater. 因此,如果此对象小于传递给compareTo()的对象,则返回-,如果等于0,则返回+,如果大于。

Taking that into consideration you might end up with a class that looks something like this 考虑到这一点,您可能会遇到一个看起来像这样的类

public class MyRect implements Comparable {
    int width;      //width of the rectangle will probably not change
    int height;     //this might be the value you want to compare in compareTo() 
    point position;

    ...

    //getters and setters yada yada
    public int getHeight(){
        return this.height;
    }

    ...

    @Override
    public int compareTo(Object otherRect){

        // if this rectangle's height is greater than otherRect the difference should 
        // be positive, if equal 0, and if less than the difference will be negative
        // exactly as specification for compareTo() states.

        return this.height - (MyRect)otherRect.getHeight();
    }
}

Obviously I've left a lot out, but that should get you pointed in the right direction. 显然,我遗漏了很多东西,但这应该使您指向正确的方向。 Play around with it and see what you come up with. 试一试,看看您会想到什么。 Happy coding! 编码愉快!

Comparabl e is an interface that should be implemented by a class that can be sorted. 比较器是应该由可以排序的类实现的接口。

To implement Comparable you simply implement a method compareTo , which compares the given object to another object. 要实现Comparable,您只需实现一个compareTo方法,它将给定对象与另一个对象进行比较。

If you have an object named Foo that can be sorted, Foo should implement Comparable. 如果您有一个名为Foo的对象可以排序,则Foo应该实现Comparable。

This allows you to sort a collection of Foo objects. 这使您可以对Foo对象的集合进行排序。

class Foo implements Comparable {
    Integer fooIndex;

    compareTo(Object otherObject) {
        Foo otherFoo = (Foo) otherObject;
        return this.fooIndex.compareTo(otherFoo.fooIndex);
    }
}

The above is a example of a simple compareTo method. 上面是一个简单的compareTo方法的示例。

Note that it doesn't check for null, or check whether or not the cast to Foo is possible. 请注意,它不会检查是否为null,也不会检查是否可以强制转换为Foo。

The above implementation allows you to do this: 上面的实现允许您执行以下操作:

List<Foo> fooList = createFooList();
Collections.sort(fooList);

Even better, you can implement a typed Comparable interface (possibly more confusing). 更好的是,您可以实现类型化的 Comparable接口(可能更令人困惑)。

This allows you to avoid casting: 这样可以避免强制转换:

Class Foo implements Comparable<Foo> {
    Integer fooIndex;

    compareTo(Foo otherFoo) {
        return this.fooIndex.compareTo(otherFoo.fooIndex);
    }
}

Implementing Comparable<T> interface depends on the objects of the class you want to sort. 实现Comparable<T>接口取决于要排序的类的对象。 The compareTo(T) method the implementation can be delegated to the instance fields of this class to determine the object ordering. 可以将实现的compareTo(T)方法委托给此类的实例字段,以确定对象的顺序。

Initially the objects of the class T are held in a collection List<T> list . 最初,类T的对象保存在集合List<T> list With the Comparable interface you can sort the collection in two ways: Collections.sort(list); 使用Comparable接口,您可以通过两种方式对集合进行排序: Collections.sort(list); or Set set = new TreeSet(list); Set set = new TreeSet(list); . The Collections class sorts the original list and the The TreeSet(list) creates a new sorted collection.For both these ways to work the objects in the list have to implement the Comparable interface. Collections类对原始列表进行排序,而TreeSet(list)创建一个新的排序后的集合。对于这两种工作方式,列表中的对象都必须实现Comparable接口。

The sorting algorithm used is mergesort for the Collections class and it cannot be changed. 所使用的排序算法是Collections类的mergesort,并且无法更改。 The Collections.sort() method delegates the task of sorting the elements to Arrays.sort(list.toArray()) . Collections.sort()方法将元素排序任务委托给Arrays.sort(list.toArray()) Internally the Arrays class casts the object to a Comparable and calls the compareTo() method to perform the comparison of elements. 在内部,Arrays类将对象强制转换为Comparable,然后调用compareTo()方法执行元素比较。

So if you're interested in performing selection sort or insertion sort then you can follow the JDK strategy. 因此,如果您对执行选择排序或插入排序感兴趣,则可以遵循JDK策略。 A class which implements the various sorting algorithms can be implemented which will take an array of objects that implement the Comparable interface. 可以实现实现各种排序算法的类,该类将采用实现Comparable接口的对象数组。

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

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