问题感觉很无脑,一个朋友突然问的。 没有上下文的情况,如有一个User类,里边有字段(对应表的唯一标识),private String uid。如何每次new一个User对象,让里边的uid都不重复。 我问他具体还有什么上下文,他也说不出,就说他去面试一个公司里的一道笔试题,过多的他也记不住了。 问:1)有无方法解决? 2)如果有上下文,如何解决? [该贴被kossin于2009-04-22 19:00修改过]
找到原题了 创建类A,确保有两个属性id(唯一),name和age 。设置main函数 创建n个A类对象并加入到hashmap对象当中。
要求:1。根据年龄对hashmap中的对象进行排序。并输出结果。
如下:
id name age
123 张三 1
134 lili 3
1789 teck 9
1 jack 11
根据如上所述,写出你的答题思路,
import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.UUID;
public class User implements Comparable {
private String id; private String name; private int age;
public User(String name, int age) { this.id = UUID.randomUUID().toString(); this.name = name; this.age = age; }
public String getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public int getAge() { return age; }
public void print() { System.out.println(this.id + " " + this.name + " " + this.age); }
public int compareTo(Object o) { if (o instanceof User) { User temp = (User) o; if (temp.getAge() > this.age) { return -1; } else if (temp.getAge() < this.age) { return 1; } else { return 0; } } return 1; }
public static void main(String[] args)
{
Map
hm.put(u1.getId(), u1); hm.put(u2.getId(), u2); hm.put(u3.getId(), u3); hm.put(u4.getId(), u4); hm.put(u5.getId(), u5); hm.put(u6.getId(), u6); hm.put(u7.getId(), u7); hm.put(u8.getId(), u8);
Collection
Object[] users = c.toArray(); Arrays.sort(users); for (Object user : users) { User u=(User) user; u.print(); }
} }
以上是我的解法,呵呵,欢迎大家拍砖。。。。。。
受益了,多谢啊!