English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Dear all,
My friend send me typical java puzzle about java.util.ArrayList
which is getting messy. Please help me out. It's not a homework.

import java.util.*;
public class MyInt ______ ________ {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i) { this.i = i; }
public String toString() { return Integer.toString(i); }
________ int ___________ {
MyInt i2 = (MyInt)o;
return ________;
}
}

Hints , fill the underlines with below :
implements
extends
Sortable
Object
Comparable
protected
public
i = i2.i
i
i2.i=i
compare(MyInt o, MyInt i2)
compare(Object o, Object i2)
sort(Object o) sort(MyInt o)
compareTo(MyInt o)
compareTo(Object o)

2006-08-27 21:39:40 · 2 answers · asked by K Ban 2 in Computers & Internet Programming & Design

import java.util.*;
public class MyInt implements Comparable {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new MyInt(2));
list.add(new MyInt(1));
Collections.sort(list);
System.out.println(list);
}
private int i;
public MyInt(int i) { this.i = i; }
public String toString() { return Integer.toString(i); }
public int compareTo(Object o){
MyInt i2 = (MyInt)o;
return i;
}
}


output :
E:\>javac MyInt.java
Note: MyInt.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

E:\>java MyInt
[1, 2]

2006-08-27 22:51:32 · update #1

2 answers

i never was good in java when i learnt it. just here to know the answers though.

2006-08-27 21:58:19 · answer #1 · answered by mei mei 4 · 0 0

my guess is the first one is implements Comparable

second: public int compareTo(Object o)

third: return i2.i - i;

none of the stuff matches for the third line - check interface Comprable in javadocs - there is no comparison you've been given, and even if it says == instead of = (which is a big difference) - it does not match what compareTo should return.

and yes, this is a homework

2006-08-28 05:49:10 · answer #2 · answered by Bruno 3 · 0 0

fedest.com, questions and answers