java速度入门三

数组操作:

compareNew.java

//use the function:sort();binarySearch();fill();equals();
import java.util.Arrays;
import java.util.Comparator;
//define a class that we could ignore the letter's case when sort array
class compareNew implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s1.toLowerCase().compareTo(s2.toLowerCase());
}

}


array.java
public class array {

public static void main(String args[])
{
int[] aa=new int[10];
String[] ss=new String[]{"w1","dwT","Aqs","Cda","Bsw","bss"};
//filling the array
Arrays.fill(aa,10);
System.out.println("array a: ");
for(int i=0;i<aa.length;i++)
{
System.out.print(aa[i]);

}
System.out.println();
System.out.println("array ss: "+Arrays.asList(ss));
//sort array by the default setting
Arrays.sort(ss);
System.out.println("After sorting ss: "+Arrays.asList(ss));
System.out.println("Hello,java!");
//sort array by the our own function
Arrays.sort(ss,new compareNew());
System.out.println("Another sorting ss: "+Arrays.asList(ss));
int location=Arrays.binarySearch(ss, "w1");
System.out.println("The location of w1 is "+(location+1)+"!");
}
}
简单实现了数组的搜索,查找,排序。

字符串操作:

Apple.java

//test the connect of String and object
public class Apple {
private String name;
public String getName()
{
return name;
}
public void setName(String s)
{
this.name=s;
}
public String toString()
{
String str="I'm an apple,my name is "+name;
return str;
}
public static void main(String[] args)
{
Apple object=new Apple();
object.setName("App");
System.out.println("Hello,"+object);
}
}


TestStringBuilder.java

//The useage of StringBuilder
import java.lang.*;
public class TestStringBuilder {
public static void main(String[] args)
{
String s="";
StringBuilder builder=new StringBuilder();
long startTime,endTime;
System.out.println("Please wait。。。");
//use the default function
startTime=System.currentTimeMillis();
for(int i=0;i<10000;i++) s+=i;
endTime=System.currentTimeMillis();
System.out.println("The cost of time: "+(endTime-startTime));
//use StringBuilder
startTime=System.currentTimeMillis();
for(int i=0;i<10000;i++) builder.append(i+"");
endTime=System.currentTimeMillis();
System.out.println("The cost of time by StringBuilder: "+(endTime-startTime));

}
}
运行结果:
Please wait。。。
The cost of time: 1371
The cost of time by StringBuilder: 9

主要要说一下字符串和对象的连接,默认是执行对象的toString方法,即将对象的全路径名称和地址,上面重载了toString方法。

第二个class是StringBuilder的用法,似乎会很快!

你可能感兴趣的:(java)