第八题
集合排序可以用java.lang.Comparable接口或者java.util.Comparator接口来实现。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Plural{
private double x;
private double y;
public double getX () {
return x;
}
public void setX (double x) {
this .x = x;
}
public double getY () {
return y;
}
public void setY (double y) {
this .y = y;
}
public Plural () {
x = 0 ; y = 0 ;
}
public Plural (double xx, double yy) {
x = xx; y = yy;
}
public void show () {
if (y == 0 )
System.out.println(x);
else
System.out.println(x + " + " + y + "i" );
}
}
class PluralComparator implements Comparator<Plural> {
@Override
public int compare (Plural o1, Plural o2) {
return o1.getX() < o2.getX() ? -1 : 1 ;
}
}
public class Q_8 {
public static void main (String[] args) {
List<Plural> lst = new ArrayList<>();
lst.add(new Plural(2.1 , 3.5 ));
lst.add(new Plural(1.4 , 8.2 ));
lst.add(new Plural(3.4 , 2 ));
Comparator<Plural> ascComparator = new PluralComparator();
Comparator<Plural> descComparator = Collections.reverseOrder(ascComparator);
Collections.sort(lst, descComparator);
for (Plural p : lst)
p.show();
}
}
第十题
这题我使用HashMap来储存, 以Class为key,以String为value
import java.util.HashMap;
class ExceptionCol{
@SuppressWarnings("rawtypes" )
public HashMap<Class, String> hm = new HashMap<>();
public ExceptionCol () {
hm.put(NullPointerException.class, "空指针异常" );
hm.put(ArithmeticException.class, "除数为0" );
}
public void add (Class c, String s) {
hm.put(c, s);
}
}
public class Q_10 {
public static void main (String[] args) {
ExceptionCol ec= new ExceptionCol();
Class c = NullPointerException.class;
System.out .println(ec.hm.containsKey(c));
}
}