随机生成一个汉字
/**
* 随机生成一个汉字
* @return
* @throws UnsupportedEncodingException
*/
public static String createStr() throws UnsupportedEncodingException {
String str = null;
int hightPos, lowPos; // 定义高低位
Random random = new Random();
hightPos = (176 + Math.abs(random.nextInt(39)));// 获取高位值
lowPos = (161 + Math.abs(random.nextInt(93)));// 获取低位值
byte[] b = new byte[2];
b[0] = (new Integer(hightPos).byteValue());
b[1] = (new Integer(lowPos).byteValue());
str = new String(b, "GBk");// 转成中文
return str;
}
排序
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
class Game{
private String materia;
public String getMateria() {
return materia;
}
public void setMateria(String materia) {
this.materia = materia;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
private String color;
private String shape;
private int size;
public Game(String materia,String color,String shape,int size){
this.materia=materia;
this.color=color;
this.shape=shape;
this.size=size;
}
@Override
public String toString(){
return materia+">"+color+">"+shape+">"+size;
}
}
/**
* 裁判类又称比较器.为了更好控制比较内容用了枚举
* @author lenovo
*
*/
class K1 implements Comparator{
public enum materiaEnum {//木材好于钢材好于合金好于塑料
wood,steel,alloy,plastic;
}
public int compare(Object o1, Object o2) {
//只有game类型才有比较的意义,如果不是该类型就让它相等不添加
if ((o1 instanceof Game)&&(o2 instanceof Game)) {
Game g1=(Game)o1;
Game g2=(Game)o2;
int x=0;
for (int i = 0; i < materiaEnum.values().length; i++) {
if (g1.getMateria().equals(materiaEnum.values()[i].toString())) {
x=i;
break;
}
}
int y=0;
for (int i = 0; i <materiaEnum.values().length; i++) {
if (g2.getMateria().equals(materiaEnum.values()[i].toString())) {
y=i;
break;
}
}
int m=x-y;
if (m!=0) {
return m;
}
else {
int c=g1.getColor().compareTo(g2.getColor());
if (c!=0) {
return c;
}
else {
int s=g1.getShape().compareTo(g2.getShape());
if (s!=0)return s;
return g1.getSize()-g2.getSize();
}
}
}
return 0;
}
}
public class TreeSetGame {
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Set gSet=new TreeSet<Game>(new K1());
gSet.add(new Game("wood","red","rectangle",1));
gSet.add(new Game("steel","red","rectangle",2));
gSet.add(new Game("wood","red","rectangle",3));
gSet.add(new Game("plastic","red","rectangle",3));
System.out.println(gSet);
}
}