1.定义一个学生类Student,具有年龄age和姓名name两个属性,并通过实现Comparable接口提供比较规则(返回两个学生的年龄差), 定义测试类Test,在测试类中定义测试方法Comparable getMax(Comparable c1, Comparable c2)完成测试
Student
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student() {
super();
}
public Student(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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student s) {
Student student = (Student) s;
return this.getAge() - student.getAge();
}
}
StudentTest
public class StudentTest {
public static void main(String[] args) {
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 30);
if (getMax(s1, s2) < 0) {
System.out.println("年龄大的是->" + s2);
} else {
System.out.println("年龄大的是->" + s1);
}
}
public static int getMax(Comparable<Student> c1, Comparable<Student> c2) {
return c1.compareTo((Student) c2);
}
}
2.模拟ArrayList集合自定义一个集合类MyArrayList,完成添加和删除功能的泛型设计,定义测试类完成测试
MyArrayList
public class MyArrayList<E> {
// 默认大小
private static final int DEFAULT_CAPACITY = 10;
// 找不到值为-1
public static final int ELEMENT_NOT_FOUND = -1;
// 集合大小
private int size;
// 存放元素的数组
private E[] elements;
// 构造方法
public MyArrayList() {
clear();
}
/**
*
* @Title: clear
* @Description: 清空集合
* @param:
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public void clear() {
size = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
/**
*
* @Title: ensureCapacity
* @Description: 开辟一个新的数组,扩容操作
* @param: @param newCapacity
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
@SuppressWarnings("unchecked")
public void ensureCapacity(int newCapacity) {
if (newCapacity < size) {
return;
}
E[] oldElements = elements;
// 新建一个数组
elements = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
elements[i] = oldElements[i];
}
}
/**
*
* @Title: size
* @Description: 返回集合大小
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public int size() {
return size;
}
/**
*
* @Title: isEmpty
* @Description: 返回集合是否为空
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public boolean isEmpty() {
return size() == 0;
}
/**
*
* @Title: trimToSize
* @Description: 修改指定大小
* @param:
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public void trimToSize() {
ensureCapacity(size());
}
/**
*
* @Title: get
* @Description: 获取指定索引的元素
* @param: @param index
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public E get(int index) {
rangeCheck(index);
return elements[index];
}
/**
*
* @Title: indexOf
* @Description: 查看元素的索引
* @param: @param element
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public int indexOf(E element) {
if (element == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null)
return i;
}
} else {
for (int i = 0; i < size; i++) {
if (element.equals(elements[i]))
return i;
}
}
return ELEMENT_NOT_FOUND;
}
/**
*
* @Title: contains
* @Description: 是否包含指定元素
* @param: @param element
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public boolean contains(E element) {
return indexOf(element) != ELEMENT_NOT_FOUND;
}
/**
*
* @Title: set
* @Description: 修改指定索引的值
* @param: @param index
* @param: @param newElement
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public E set(int index, E newElement) {
rangeCheck(index);
E old = elements[index];
elements[index] = newElement;
return old;
}
/**
*
* @Title: add
* @Description: 直接从尾部插入
* @param: @param addElement 添加的元素
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public boolean add(E addElement) {
add(size(), addElement);
return true;
}
/**
*
* @Title: add
* @Description: 指定索引位置添加元素
* @param: @param index 索引
* @param: @param addElement 添加的元素
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public void add(int index, E addElement) {
// 先判断是否需要扩容
if (elements.length == size()) {
ensureCapacity(size() * 2 + 1);
}
// 集合元素往后移动
for (int i = size; i > index; i--) {
elements[i] = elements[i - 1];
}
elements[index] = addElement;
size++;
}
/**
*
* @Title: remove
* @Description: 删除指定索引的元素
* @param: @param index
* @param: @return
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public E remove(int index) {
E removeElement = elements[index];
// 集合的元素统一向前移动
for (int i = index; i < size() - 1; i++) {
elements[i] = elements[i + 1];
}
// 长度减1
size--;
return removeElement;
}
/**
*
* @Title: rangeCheck
* @Description: 判断索引是否合法
* @param: @param index
* @author: KangXiaoZhuang
* @email: ITkxz0830@163.com
*/
public void rangeCheck(int index) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException("索引越界异常!!!");
}
}
public void print() {
for (int i = 0; i < size; i++) {
System.out.print(elements[i] + " ");
}
System.out.println();
}
}
MyArrayListTest
public class MyArrayListTest {
public static void main(String[] args) {
MyArrayList<Integer> list = new MyArrayList<>();
list.add(getRandom());
list.add(getRandom());
list.add(getRandom());
list.add(getRandom());
list.add(getRandom());
list.print();
System.out.println("==========删除操作==========");
list.remove(2);
list.print();
}
public static int getRandom() {
Random random = new Random();
return random.nextInt(10);
}
}
3.定义一个泛型方法printArray,可以打印输出任何类型的数组,例如:[“小明”,”小红”,”小兰”],[1,2,3] ,定义测试类完成测试。
public class PrintArray {
public static void main(String[] args) {
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
String[] stringArray = { "小明", "小红", "小兰" };
System.out.println("整型数组元素为:");
printArray(intArray);
System.out.println("\n双精度型数组元素为:");
printArray(doubleArray);
System.out.println("\n字符型数组元素为:");
printArray(charArray);
System.out.println("\n字符串数组元素为:");
printArray(stringArray);
}
public static <T> void printArray(T[] array) {
System.out.println(Arrays.toString(array));
}
}
4.为某系统提供一个泛型接口Data,该接口可以约束非泛型类TeacherData和StudentData必须完成数据(学生、老师)的增删改查操作
Data
public interface Data<T> {
void add(T t);
void remove(T t);
void update(int index, T t);
T query(int index);
}
Student
public class Student {
private int id;
private String name;
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Student() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
StudentData
public class StudentData implements Data<Student> {
ArrayList<Student> studentList = new ArrayList<>();
@Override
public void add(Student s) {
studentList.add(s);
}
@Override
public void remove(Student s) {
studentList.remove(s);
}
@Override
public void update(int index, Student s) {
for (int i = 0; i < studentList.size(); i++) {
if (s == studentList.get(i)) {
index = i;
break;
}
}
studentList.set(index, s);
}
@Override
public Student query(int index) {
return studentList.get(index);
}
public ArrayList<Student> getArrayList() {
return this.studentList;
}
}
TeacherData
public class TeacherData implements Data<Teacher> {
ArrayList<Teacher> teacherList = new ArrayList<>();
@Override
public void add(Teacher t) {
teacherList.add(t);
}
@Override
public void remove(Teacher t) {
teacherList.remove(t);
}
@Override
public void update(int index, Teacher t) {
for (int i = 0; i < teacherList.size(); i++) {
if (t == teacherList.get(i)) {
index = i;
break;
}
}
teacherList.set(index, t);
}
@Override
public Teacher query(int index) {
return teacherList.get(index);
}
public ArrayList<Teacher> getArrayList() {
return this.teacherList;
}
}
DataTest
public class DataTest {
public static void main(String[] args) {
DataTest dataTest = new DataTest();
dataTest.testStudent();
System.out.println("===========================================");
dataTest.testTeacher();
}
public void testStudent() {
Teacher t1 = new Teacher(13, "小红");
Teacher t2 = new Teacher(4, "小明");
Teacher t3 = new Teacher(68, "小花");
Teacher t4 = new Teacher(98, "小庄");
Teacher t5 = new Teacher(24, "小康");
TeacherData teacherData = new TeacherData();
System.out.println("添加元素");
teacherData.add(t1);
teacherData.add(t2);
teacherData.add(t3);
teacherData.add(t4);
teacherData.add(t5);
System.out.println(teacherData.getArrayList());
teacherData.remove(t1);
System.out.println("\n删除元素");
System.out.println(teacherData.getArrayList());
System.out.println("\n更新元素");
teacherData.update(2, new Teacher(66, "康小庄"));
System.out.println(teacherData.getArrayList());
System.out.println("\n查询元素");
System.out.println(teacherData.query(3));
}
public void testTeacher() {
Teacher t1 = new Teacher(1, "张三");
Teacher t2 = new Teacher(2, "李四");
Teacher t3 = new Teacher(3, "王五");
Teacher t4 = new Teacher(4, "赵六");
Teacher t5 = new Teacher(5, "田七");
TeacherData teacherData = new TeacherData();
System.out.println("添加元素");
teacherData.add(t1);
teacherData.add(t2);
teacherData.add(t3);
teacherData.add(t4);
teacherData.add(t5);
System.out.println(teacherData.getArrayList());
teacherData.remove(t1);
System.out.println("\n删除元素");
System.out.println(teacherData.getArrayList());
System.out.println("\n更新元素");
teacherData.update(0, new Teacher(8, "新教师"));
System.out.println(teacherData.getArrayList());
System.out.println("\n查询元素");
System.out.println(teacherData.query(1));
}
}
5.顺序表是线性表的顺序存储,是在计算机内存中以数组的形式保存的线性表,请完善顺序表的数据结构,顺序表的泛型类设计如下。
类名 SequenceList
构造方法 SequenceList(int capacity) 创建容量为capacity的SequenceList对象
成员方法
1.public void clear() 置空顺序表
2.public boolean isEmpty() 判断顺序表是否为空
3.public int length() 获取顺序表的元素个数
4.public T get(int i) 返回顺序表中的第i个元素
5.public void insert(int i,T t) 在顺序表的第i个元素之前插入一个元素t
6.public void insert(T t) 向顺序表中添加一个元素t
7.public T remove(int i) 删除并返回顺序表中的第i个元素
8.public int indexOf(T t) 返回顺序表中首次出现元素t的位置,若不存在返回-1
成员变量
1.private T[] eles 存储元素的数组
2.private int n 当前顺序表的长度
6.顺序表的遍历:
(1)让SequenceList实现Iterable接口,重写iterator方法;
(2)在SequenceList类内部提供一个内部类 SIterator,实现Iterable接口,重写hasNext方法和next方法。
(3)编写测试类,测试SequenceList类支持的foreach循环。
SequenceList
@SuppressWarnings("all")
public class SequenceList<T> implements Iterable<T> {
// 存储元素的数组
private T[] eles;
// 当前顺序表的长度
private int n;
// 创建容量为capacity的SequenceList对象
SequenceList(int capacity) {
eles = (T[]) new Object[capacity];
}
// 置空顺序表
public void clear() {
for (int i = 0; i < n; i++) {
eles[i] = null;
}
n = 0;
}
// 判断顺序表是否为空
public boolean isEmpty() {
return n == 0;
}
// 获取顺序表的元素个数
public int length() {
int count = 0;
for (int i = 0; i < n; i++) {
if (eles[i] != null) {
count++;
}
}
return count;
}
// 返回顺序表中的第i个元素
public T get(int i) {
return eles[i];
}
// 在顺序表的第i个元素之前插入一个元素t
public void insert(int i, T t) {
for (int j = n - 1; j >= i; j--) {
eles[j + 1] = eles[j];
}
eles[i] = t;
n++;
}
// 向顺序表中添加一个元素t
public void insert(T t) {
insert(n, t);
}
// 删除并返回顺序表中的第i个元素
public T remove(int i) {
T oldelement = eles[i];
for (int j = i + 1; j < n; j++) {
eles[j - 1] = eles[j];
}
eles[--n] = null;
return oldelement;
}
// 返回顺序表中首次出现元素t的位置,若不存在返回-1
public int indexOf(T t) {
if (eles == null) {
for (int i = 0; i < n; i++) {
if (eles[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < n; i++) {
if (eles.equals(eles[i])) {
return i;
}
}
}
return -1;
}
public void print() {
for (T t : eles) {
if (t != null) {
System.out.print(t + ",");
}
}
}
@Override
public Iterator<T> iterator() {
return new SIterator<T>(this);
}
class SIterator<T> implements Iterator<T> {
private int current = 0;
private SequenceList<T> sequenceList;
public SIterator(SequenceList<T> sequenceList) {
this.sequenceList = sequenceList;
}
@Override
public boolean hasNext() {
// 判断是否还有下一个
return current < sequenceList.length();
}
@Override
public T next() {
// 看是否还有下一个
if (!hasNext()) {
throw new NoSuchElementException();
}
return sequenceList.eles[current++];
}
public void remove() {
SequenceList.this.remove(--current);
}
}
}
SequenceListTest
public class SequenceListTest {
public static void main(String[] args) {
test01();
}
public static void test01() {
SequenceList<Integer> sequenceList = new SequenceList<Integer>(10);
System.out.println("添加元素");
for (int i = 0; i < 10; i++) {
sequenceList.insert(i);
}
sequenceList.print();
System.out.println();
System.out.println("清空集合");
sequenceList.clear();
System.out.println("集合大小:" + sequenceList.length());
System.out.println("添加元素");
for (int i = 10; i < 20; i++) {
sequenceList.insert(i);
}
sequenceList.print();
System.out.println();
System.out.println("集合大小:" + sequenceList.length());
System.out.println("集合是否为空:" + sequenceList.isEmpty());
System.out.println("索引5的元素是:" + sequenceList.get(5));
System.out.println("删除索引5的元素:" + sequenceList.remove(5));
sequenceList.print();
System.out.println();
System.out.println("迭代器遍历");
// 迭代器遍历
Iterator<Integer> iterator = sequenceList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}