Java 泛型与实现类

Java 泛型与实现类

一、泛型

1. 定义

将对象的类型作为参数,指定到其他类或者方法上,从而保证类型转换的安全性和稳定性。

本质——参数化的类型。

2. 使用

泛型集合可以约束集合内的元素类型:

典型泛型集合ArrayList<E>、HashMap<K,V>,<E>、<K,V>表示该泛型集合中的元素类型。

注:泛型集合中的数据不再转换为Object。

public class Test {

	/*
	 * 可以存储各类新闻标题(包含ID、名称、创建者) 可以获取新闻标题的总数 可以逐条打印每条新闻标题的名称
	 */
	public static void main(String[] args) {
		// 创建3新闻标题类对象
		NewsTitle nt1 = new NewsTitle(1001, "合肥新站区和肥西各新增1例新冠肺炎感染者", "合肥日报");
		NewsTitle nt2 = new NewsTitle(1002, "合肥今日有暴雨,局部地区特大暴雨", "张三");
		NewsTitle nt3 = new NewsTitle(1003, "震惊,程序员每天竟然喜欢干这件事", "李四");
		NewsTitle nt4 = new NewsTitle(1004, "安徽泗县昨日新增新冠肺炎无症状感染者23例", "安徽日报");

		// 准备集合容器,调用ArrayList类的无参构造方法,创建一个默认长度为10的集合容器
        /*
        	原代码:
        	ArrayList al = new ArrayList();
        */
		ArrayList<NewsTitle> al = new ArrayList<NewsTitle>();

		// 将创建的新闻标题对象存储到al集合中
		al.add(nt1);
		al.add(nt3);
		al.add(nt2);

		// 获取新闻标题的总数----》获取集合中元素的个数
		// int size():返回列表中的元素个数
		int size = al.size();
		System.out.println("集合中元素的个数:" + size);

		for (int i = 0; i < al.size(); i++) {
            /*
                原代码:
                Object obj = al.get(i);
                NewsTitle newsTile = (NewsTitle) obj;
       		 */
			NewsTitle newsTile = al.get(i);
			System.out.println(newsTile.getId()+"--"+newsTile.getName());
		}
    }
}

二、Collections类常用方法

1. Collections与Collection区别

Collections:集合的操作类。

Collection:集合接口。

2. 常用静态方法

① sort():排序

② binarySearch():查找

③ max()\min():查找最大\最小值

public class Demo01 {

	public static void main(String[] args) {
		//创建一个ArrayList集合对象,里面存储String类型的数据
		ArrayList<String> al = new ArrayList<String>();
		
		al.add("wseurfhu");
		al.add("dsfsdf");
		al.add("asdewre");
		al.add("sdfsf");
		al.add("afhth");
		
		System.out.println("集合排序之前:");
		for (String string : al) {
			System.out.println(string);
		}
		
		// 1.Collections.sort():对集合进行排序
		Collections.sort(al);
		
		System.out.println("集合排序后:");
		for (String string : al) {
			System.out.println(string);
		}
		
		// 2.int binarySearch(集合名,查找的数据):查找元素,返回查找元素所在的下标,如果查找不到元素,返回一个负值。 注意:使用该方法之前,对先对集合进行升序排序,否则不能保证查询结果的正确性
		int index = Collections.binarySearch(al, "sdfsfgj");
		System.out.println(index);
		
		// 3.max()/min():求集合中的最大值最小值
		String max = Collections.max(al);
		System.out.println(max);
		String min = Collections.min(al);
		System.out.println(min);
		
		Collections.reverse(al);
		
		System.out.println("集合元素反转之后:");
		Iterator<String> it=al.iterator();
		while(it.hasNext()){
			String str = it.next();
			System.out.println(str);
		}
	}
}

自定义类存储在集合中,要想使用sort()方法进行排序,那么该自定义类要实现Comparable接口,重写Comparable接口中的compareTo()方法,定义排序规则。

// 先继承接口Comparable才可重写compareTo方法,Comparable<T>也是泛型
public class Student implements Comparable<Student> {

	private String name;
	private int stuId;

	public Student() {
		super();
	}

	public Student(String name, int stuId) {
		super();
		this.name = name;
		this.stuId = stuId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getStuId() {
		return stuId;
	}

	public void setStuId(int stuId) {
		this.stuId = stuId;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", stuId=" + stuId + "]";
	}

	@Override
	public int compareTo(Student student) {
		//比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。
		if(this.stuId<student.stuId){
			return -1;
		}else if(this.stuId==student.stuId){
			return 0;
		}else{
			return 1;
		}
	}

}

实现类:

public class StudentTest {
	public static void main(String[] args) {
		//创建4个Student类对象
		Student stu1 = new Student("张三", 1001);
		Student stu2 = new Student("李四", 1002);
		Student stu3 = new Student("王五", 1003);
		Student stu4 = new Student("赵六", 1004);
		
		//创建ArrayList集合对象
		ArrayList<Student> al = new ArrayList<Student>();
		
		al.add(stu3);
		al.add(stu2);
		al.add(stu4);
		al.add(stu1);
		
		System.out.println("集合排序前:");
		for (Student student : al) {
			System.out.println(student);
		}
		
		//自定义类存储在集合中,要想使用sort()方法进行排序,那么该自定义类要实现Comparable接口,重写Comparable接口中的compareTo()方法,定义排序规则
		Collections.sort(al);
		
		System.out.println("集合排序后:");
		for (Student student : al) {
			System.out.println(student);
		}
	}
}

三、实现类

1. Enum枚举类

[Modifier] enum enumName{

enumContantName1

[,enumConstantName2…[;]]

//[field,method]

}

例如:

Enum枚举类:

public enum Genders {
	//枚举是由一组固定常量组成的类型,, 东方不败
}

使用定义的枚举类型“Genders”声明变量“gender”。

public class Student {
	public String name;
	public Genders gender;
}

实现类:

public class StudentTest {
	public static void main(String[] args) {
		//使用无参构造方法创建对象
		Student stu = new Student();
		//给属性赋值
		stu.name = "张三";
		stu.gender = Genders.东方不败;
		System.out.println(stu.name+"--"+stu.gender);
	}
}

2. 包装类

① 包装类把基本类型数据转换为对象,每个基本类型在java.lang包中都有一个相应的包装类

②作用:

1)提供了一系列实用的方法。

2)集合不允许存放基本数据类型数据,存放数字时,要用包装类型。

public class Demo01 {

	public static void main(String[] args) {
		// 所有包装类都可将与之对应的基本数据类型作为参数,来构造它们的实例
		// 除Character类外,其他包装类可将一个字符串作为参数构造它们的实例(对于Number类型的对象,字符串需要是“数字形式的字符串”,也不能传递一个null值)
		byte byt = 10;
		// byte1是一个对象,这个对象里存储了数据byt
		Byte byte1 = new Byte(byt);
		Byte byte2 = new Byte("123");
		// Byte byte3 = new Byte("abc");//NumberFormatException
		System.out.println(Byte.MAX_VALUE);
		System.out.println(Byte.MIN_VALUE);
		System.out.println(byte2);

		short sho = 100;
		Short short1 = new Short(sho);
		Short short2 = new Short("1343");

		int num = 1000;
		Integer integer = new Integer(num);
		Integer integer2 = new Integer("1122");

		long lon = 10000L;
		Long long1 = new Long(lon);
		Long long2 = new Long("156");

		float flo = 100.5F;
		Float float1 = new Float(flo);
		Float float2 = new Float("12.5");

		double dou = 99.88;
		Double double1 = new Double(dou);
		Double double2 = new Double("12.55");

		boolean bool = true;
		Boolean boolean1 = new Boolean(bool);
		Boolean boolean2 = new Boolean("sdsa");//字符串里的内容为true(不区分大小写)的时候,对象里存储的是true,其它所有情况都为false
		System.out.println(boolean2);

		char cha = '好';
		Character character1 = new Character(cha);
		
		System.out.println(Short.MAX_VALUE);
		System.out.println(Short.MIN_VALUE);
	}
}

注意事项:

1)Boolean类构造方法参数为String类型时,若该字符串内容为true(不考虑大小写),则该Boolean对象表示true,否则表示false

2)当Number包装类构造方法参数为String 类型时,字符串不能为null,且该字符串必须可解析为相应的基本数据类型的数据,否则编译不通过,运行时会抛出NumberFormatException异常

3. 包装类常用方法

XXXValue():包装类转换成基本类型。

Integer integerId=new Integer(25);
int intId=integerId.intValue();

toString():以字符串形式返回包装对象表示的基本类型数据(基本类型->字符串)。

String sex=Character.toString('男');
String id=Integer.toString(25);

String sex='男'+"";
String id=25+"";

parseXXX():把字符串转换为相应的基本数据类型数据(Character除外)(字符串->基本类型)。

int num=Integer.parseInt("36");
boolean bool=Boolean.parseBoolean("false");

valueOf():

1)所有包装类都有如下方法(基本类型->包装类)

public static Type valueOf(type value)

Integer intValue = Integer.valueOf(21);

2)n除Character类外,其他包装类都有如下方法(字符串->包装类)

public static Type valueOf(String s)

 Integer intValue = Integer.valueOf("21");

4. 装箱和拆箱

装箱:基本类型转换为包装类的对象。

拆箱:包装类对象转换为基本类型的值。

基本类型和包装类的自动转换:

Integer intObject = 5;
int intValue = intObject;

特点:

① JDK1.5后,允许基本数据类型和包装类型进行混合数学运算。

ava
Integer intValue = Integer.valueOf(21);


2)n除Character类外,其他包装类都有如下方法(字符串->包装类)

public static Type valueOf(String s)

```java
 Integer intValue = Integer.valueOf("21");

4. 装箱和拆箱

装箱:基本类型转换为包装类的对象。

拆箱:包装类对象转换为基本类型的值。

基本类型和包装类的自动转换:

Integer intObject = 5;
int intValue = intObject;

特点:

① JDK1.5后,允许基本数据类型和包装类型进行混合数学运算。

② 包装类并不是用来取代基本数据类型的,在基本数据类型需要用对象表示时使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Glensea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值