Java的API及Object类、String类、字符串缓冲区

Java API

1.1定义

API: Application(应用) Programming(程序) Interface(接口)

Java API就是JDK中提供给开发者使用的类,这些类将底层的代码实现封装了起来,不需要关心这些类是如何实现的,只知道如何使用即可。

JDK安装目录下有个src.zip文件,里面是所有Java类的源文件。可以查看源码。

但是不方便,所以用api手册查,

 

打开后,点显示,索引,输入想查看的类,选择第一项,就可以了

 

 

可以查看:类的继承体系,接口,子类,成员变量,构造方法,成员方法。就可以学会这个类的使用方法了。

 

2 Object

Object类是Java语言中的根类,即所有类的父类。

它中描述的所有方法,子类都可以使用。

所有类在创建对象的时候,最终找的父类就是Object

2.1equals方法

用于比较两个对象是否相同,实际是使用两个对象的内存地址在比较。

例:

public class Person {
	private String name;
	private int age;
	
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	};
}
public class Test {
	public static void main(String[] args) {
		Person p1=new Person("张三",18);
		Person p2=new Person("李四",18);		
		System.out.println(p1.equals(p2)); //比的是地址
		System.out.println(p1==p2); //比的是地址
	}
}

 

都比的地址,可以查看一下equals的源码(放在上面,ctrl+点击

 

可以看到,Object中的equals方法,就是用的==比较。

比较地址没有意义,比较内容才有意义,比如这里要判断同龄人,

所以需要重写equals方法 (一般Object里的方法都要重写的)

 

但是直接这样写不对,因为传进来的是一个Person对象,而参数objObject类型,这是多态,所以obj是访问不到age的,这时必须向下转型,转成Person类型才可以,用instanceof做判断:

 

但是,还是报错:

 

因为这个equals方法的返回值是boolean,所以如果转型失败呢,就得不到正确的返回值了,所以要加一个return false;

//比较年龄
	public boolean equals(Object obj) {
		if(obj instanceof Person){
			Person p=(Person)obj;
			return this.age==p.age;
		}	
		return false;
	}	

这时再运行test中的p1.equals(p2)

 

这个方法还需要提高健壮性,如果传入了一个null呢,如果把对象本身传过去了呢?所以最后为:

public class Person {
	private String name;
	private int age;
	
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	};
	
	//比较年龄
	public boolean equals(Object obj) {
		if(obj==null){  //传了null
			return false;
		}		
		if(obj==this){  //把自己传进来
			return true;
		}	
		if(obj instanceof Person){ //向下转型
			Person p=(Person)obj;
			return this.age==p.age;
		}	
		return false;  //转型失败返回false
	}	
}

而且这个重写方法也有快捷添加方式:

Person类中,写上equals,然后Alt+/,就出现提示了

回车即可:

String里面的equals就是比较值:

public class Test3 {
	public static void main(String[] args) {
		String s1="abc";
		String s2="abc";
		String s3="123";
		System.out.println(s1.equals(s2));
		System.out.println(s1.equals(s3));			
	}
}

 

这就是因为String类重写了equals方法,可以查一下看看:

所以自己写的类,一定要重写equals方法,才能进行值的比较,而且注意必须向下转型。

2.2 toString方法

返回该对象的字符串表示。

例:还是上面那个Person类,

public class Test2 {
	public static void main(String[] args) {
		Person p1=new Person("小红",18);
		System.out.println(p1);
		System.out.println(p1.toString());
	}
}

 

两个结果都是地址,说明直接打印引用数据类型,就是在自动调用toString方法。

同样的,地址没什么用,需要的是对象的内容,也就是能把对象的属性打印出来就好了,所以要重写toString法。

public String toString() {		
	return "name="+name+",age="+age;
}

 

这个也有快捷方式点出来:

右键--Source--Generate toString()... 选择上属性,

 

出来是是这样的:

 

Test结果为:

 

这个格式更好看。

同样的,字符串可以直接打印内容,就是因为重写了toString方法:

public class Test4 {
	public static void main(String[] args) {
		String s="abc";
		System.out.println(s);
		System.out.println(s.toString());
	}
}

3 String

String 类代表字符串所有字符串字面值(如 "abc" )都作为此类的实例实现(对象)

3.1字符串是常量

字符串的本质是一个字符的数组。

例:

public class Demo01 {
	public static void main(String[] args) {
		String str1="abc";	
		String str2="abc";	
		String str3=new String("abc");
		
		System.out.println(str1==str2);
		System.out.println(str1.equals(str2));	
		
		System.out.println();
		
		System.out.println(str1==str3);
		System.out.println(str1.equals(str3));			
	}
}

 

理解:

堆里有一块区域 常量池,(用final修饰的成员变量都进常量池)

字符串就在常量池里。

引号就是一个对象,一旦创建不能改变。

而这种

String s=”abd”;

S=”123”;

改的是变量s,而abc123 都不会被改变。

String str1="abc";

String str3=new String("abc");

str1创建,在内存中只有一个对象。这个对象在字符串常量池中

str3创建,在内存中有两个对象:一个new的对象在堆中,一个字符串本身对象,在字符串常量池中。

 

图:

3.2 String类构造方法

例:

//string构造方法
public class Demo02 {
	public static void main(String[] args) {
		 method01();
		 method02();
		 method03();
	}
	public static void method01(){
		System.out.println("method01的结果:");
		byte[] bytes={65,66,67,68};
		String str=new String(bytes);
		System.out.println(str);
		
		byte[] bytes2={-65,-66,-67,-68};
		String str2=new String(bytes2);
		System.out.println(str2);		
	}
	
	public static void method02(){
		System.out.println();
		System.out.println("method02的结果:");
		byte[] bytes={65,66,67,68};
		String str=new String(bytes,1,2);
		System.out.println(str);
	}
	
	public static void method03(){
		System.out.println();
		System.out.println("method03的结果:");
		//字符数组转字符串
		char[] ch={'中','a','2','A'};
		String str=new String(ch);
		System.out.println(str);
		
		String str2=new String(ch,0,1);		
		System.out.println(str2);
	}	
}

 

说明:

1)method01中,打印的是ASCII值对应的字符:

http://www.runoob.com/tags/html-ascii.html

只用记三个值就好:

048

A65

a97

字节byte范围的会自动走ASCII,例:

public class Test {
	public static void main(String[] args) {
		char ch=97;
		char ch2='a';
		int i=(int)ch2;
		
		System.out.println(ch);
		System.out.println(ch2);
		System.out.println(i);		
	}
}

2)method01中,负数是打印汉字。一个汉字两个字节。

如果只写了三个字符,那么第二字汉字就是乱码:

3)method03字符数组转字符串,以后IO流时会再遇到

4method02new String(bytes,1,2);

两个数字参数为:起点(下标从0开始),个数

3.3 String常用方法

1)字符串的长度

public class Test {
	public static void main(String[] args) {
		String str="abcd";
		System.out.println(str.length());
	}
}

2)字符串截取

public class Test {
	public static void main(String[] args) {
		String str="chinanihao";
		String s=str.substring(5); //要有一个对象接收新的
		System.out.println(s);
	}
}

3)字符串截取:从开始索引一直截取到结束索引(不包含结束索引)

public class Test {
	public static void main(String[] args) {
		String str="chinanihao";
		String s=str.substring(5,6); //要有一个对象接收新的
		System.out.println(s);
	}
}

4)判断一个字符串是否以一个字符串前缀开始

public class Test {
	public static void main(String[] args) {
		String str="javanihao";
		boolean flag=str.startsWith("java");
		System.out.println(flag);
	}
}

 

5)判断一个字符串是否以一个字符串前缀结尾(常用于IO流中判断文件类型)

public class Test {
	public static void main(String[] args) {
		String str="Person.java";
		boolean flag=str.endsWith(".java");
		System.out.println(flag);
	}
}

6)判断一个字符串中是否包含另一个字符串

public class Test {
	public static void main(String[] args) {
		String str="javanihao";
		boolean flag=str.contains("ni");
		System.out.println(flag);
	}
}

7)获取小字符串在大字符串中第一次出现的索引,如果不存在,返回-1

public class Test {
	public static void main(String[] args) {
		String str="javanihaojava";
		int index=str.indexOf("java");
		int index2=str.indexOf("php");
		System.out.println(index);
		System.out.println(index2);
	}
}

8)字符串转字节数组 & 字符串转字符数组

public class Test {
	public static void main(String[] args) {
		String str="china";
		byte[] bytes=str.getBytes(); //字符串转字节数组
		char[] ch=str.toCharArray(); //字符串转字符数组
		
		for(int i=0;i<bytes.length;i++){
			System.out.print(bytes[i]+" ");
		}
		
		System.out.println();
		
		for(int i=0;i<ch.length;i++){
			System.out.print(ch[i]+" ");
		}
	}
}

9)比较字符串

public class Test {
	public static void main(String[] args) {
		String str="javagood";
		System.out.println(str.equals("javaGood"));
		System.out.println(str.equalsIgnoreCase("javaGood"));  //不区分大小写
	}
}

10)获取字符串对象中的内容

public class Test {
	public static void main(String[] args) {
		String str="abcdefg";
		System.out.println(str);
		System.out.println(str.toString());
	}
}

 

直接打印引用类型变量时,默认调用该类型进行重写后的toString方法。

 

10)判断是否为空的字符串

public class Test2 {
	public static void main(String[] args) {
		String str="xyz";
		boolean flag=str.isEmpty();
		System.out.println(flag);
	}
}

11)获取字符串中指定位置上的字符

public class Test2 {
	public static void main(String[] args) {
		String str="hello";
		char s=str.charAt(1);
		System.out.println(s);
	}
}

12)大小写转换

public class Test2 {
	public static void main(String[] args) {
		String str1="ABC";
		String str2=str1.toLowerCase();
		System.out.println(str2);
		
		String str3="abc";
		String str4=str3.toUpperCase();
		System.out.println(str4);		
	}
}

13)替换

public class Test2 {
	public static void main(String[] args) {
		String str="zyxhello";
		String nstr1=str.replace('z','a');
		String nstr2=str.replace("zy","ab");
		System.out.println(nstr1);
		System.out.println(nstr2);	
	}
}

14)去除字符串两端空格,中间的不会去除

public class Test2 {
	public static void main(String[] args) {
		String str="   ab c   ";
		String nstr=str.trim();
		System.out.println(nstr);	
	}
}

3.4练习

1)获取指定字符串中,大写字母、小写字母、数字的个数

public class E1 {
	public static void main(String[] args) {
		String str="ABCabcd12345";
		int big=0;
		int small=0;
		int num=0;
		for(int i=0;i<str.length();i++){
			int n=str.charAt(i);
			if(n>='A'&&n<='Z'){
				big++;
			}else if(n>='a'&&n<='z'){
				small++;
			}else if(n>='0'&&n<='9'){
				num++;
			}			
		}
		System.out.println("大写字母的个数是"+big);
		System.out.println("小写字母的个数是"+small);
		System.out.println("数字的个数是"+num);		
	}
}

2将字符串中,第一个字母转换成大写,其他字母转换成小写,并打印改变后的字符串。

public class E2 {
	public static void main(String[] args) {
		String str="abcdEFG";
		String s1=str.substring(0,1);
		String s2=str.substring(1);
		
		s1=s1.toUpperCase();
		s2=s2.toLowerCase();	
		
		System.out.println(s1+s2);
	}
}

3)在“hellojava,nihaojava,javazhenbang”中查询出现“java”的次数。

public class E3 {
	public static void main(String[] args) {		
		int count=getCount("hellojava,nihaojava,javazhenbang", "java");
		System.out.println(count+"次");		
	}
	
	public static int getCount(String big, String small){
		int count=0; 
		int index=-1;
		
		while(true){
			index=big.indexOf(small);
			if(index!=-1){
				count++;
				big=big.substring(index+1);
				//big=big.substring(index+"java".length());也可以
			}else break;	
		}
		
		return count;
	}
}

优化代码:

public class E3_2 {
	public static void main(String[] args) {
		int count = getCount("hellojava,nihaojava,javazhenbang", "java");
		System.out.println(count + "次");
	}

	public static int getCount(String big, String small) {
		int count = 0;
		int index = -1;

		while ((index = big.indexOf(small)) != -1) {
			count++;
			big = big.substring(index + 1);
		}
		return count;
	}
}

4字符串缓冲区

4.1 StringBuffer

String 是常量不可变,所以要有一个可变的。

StringBuffer是个字符串的缓冲区,就是一个容器,容器中可以装很多字符串。并且能够对其中的字符串进行各种操作。

4.1.1构造方法

StringBuffer();

StringBuffer(String str);

4.1.2常用方法

1)添加

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer();		
		sb.append("a").append('中').append(true).append(1.2);
		System.out.println(sb); //返回的是一个String类型,困为默认调的toString方法
	}
}

这里是一种用法:链式调用用一个方法后,返回一个对象,然后使用返回的对象继续调用方法。这种时候,就可以把代码写在一起。

2)删除(包含起始索引,不包含结束索引)

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		sb.delete(1,3); //包头不包尾
		System.out.println(sb);
	}
}

3)在指定位置插入元素

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		sb.insert(0,"java");
		System.out.println(sb);
	}
}

4)替换

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		sb.replace(1, 2, "hello"); //包头不包尾
		System.out.println(sb);	
	}
}

5)反转

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		sb.reverse();
		System.out.println(sb);	
	}
}

6)截取

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		String sb2=sb.substring(2);
		System.out.println(sb2);
	}
}

7删除指定位置上的字符

public class Test {
	public static void main(String[] args) {
		StringBuffer sb=new StringBuffer("abcde");	
		sb.deleteCharAt(0);
		System.out.println(sb);
	}
}

 

4.1.3 String和StringBuffer对比

public class Test {
	public static void main(String[] args) {
		StringBuffer str1=new StringBuffer("abcde");
		str1.replace(0, 4, "111");
		System.out.println("str1:"+str1);
		
		String str2="abcde";
		String str3=str2.replace("abcd", "111");
		//str2=str2.replace("abcd", "111"); 还可以这样写,更简便
		System.out.println("str2:"+str2);
		System.out.println("str3:"+str3);
	}
}

这说明,String不可变,StringBuffer可变。String进行一些操作时,一定要有另一个String变量接收(或者再赋值给本身)。而StringBuffer可以直接操作。

4.1.4练习:int[] arr = {34,12,89,68}; 打印:[34,12,89,68]

public class Test {
	public static void main(String[] args) {
		int[] arr = {34,12,89,68};		
		method2(arr);
	}
	
	public static void method2(int[] arr){
		StringBuffer str=new StringBuffer();
		str.append('[');
		for(int i=0;i<arr.length;i++){
			if(i!=arr.length-1){
				str.append(arr[i]+","); //这里不能写单引号的',',那样就是加ASCII值了
			}else{
				str.append(arr[i]+"]");
			}		
		}
		System.out.println(str);		
	}
}

4.2 StringBuilder

和StringBuffer的用法一模一样。

该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。(以后学习线程时再学)

原文地址:https://www.cnblogs.com/hzhjxx/p/10092429.html