泛型集合:
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:
1). 编译时即可检查,而非运行时抛出异常。
2). 访问时,不必类型转换(拆箱)。
3). 不同泛型之间引用不能相互赋值,泛型不存在多态。
定义泛型、实例泛型:
类:创建对象时,为类所定义的泛型,进行参数化赋值
接口:实现接口时,为接口所定义的泛型,进行参数化赋值
静态泛型:
定义在方法的返回值类型前面:、、<T extends Comparable>、<T extends Comparable<? super T>>
定义在方法的形参列表当中:<?>、<? extends Object>、<? super Integer>,不支持使用&
Collections工具类:
概念:集合工具类,定义了除了存取以外的集合常用方法。
public static <T extends Comparable<? super T>> void sort(List list) //排序,要求:必须实现Comparable,必须可与自身类型比,以及父类类型比
public static void reverse(List<?> list) //反转、倒置元素
public static void shuffle(List<?> list) //随机重置顺序
11、
public class TestMyClass {
public static void main(String[] args) {
IA ia = new MyClass();
System.out.println(ia);//输出MyClass toString,接口被继承,子类实现并重写toString
}
}
interface IA{
void ma();
}
class MyClass implements IA{
public void ma() {}
public String toString() {
return "MyClass toString()";
}
}
12、
public class TestStringBuilder {
public static void main(String[] args) {
String str = "QWERTYUIOPLKJHGFDSAZXCVBNMqwertyuioplkjhgfdsazxcvbnm1234567890";
Random ran = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8 ; i++) {
int number = ran.nextInt(3);
int result;
switch(number) {
case 0 :
result = (int)(Math.random()*25+65);
sb.append((char)result);
break;
case 1 :
result = (int)(Math.random()*25+97);
sb.append((char)result);
break;
case 2 :
sb.append(String.valueOf(new Random().nextInt(10)));
}
}
System.out.println(sb);
}
}
13、
public static void main(String[] args) {
String str = "abcd23abc34bcd";
String s = "bc";
int start = 0;
while(true){
int i = str.indexOf(s, start);
if (i==-1) break;
System.out.println(i);
start = i+s.length();
}
}
}
14、
import java.util.ArrayList;
import java.util.List;
public class Homework14 {
public static void main(String[] args) {
List<Student>list=new ArrayList<Student>();
list.add(new Student("Tom",18,100,"class05"));
list.add(new Student("Jerry",22,70,"class04"));
list.add(new Student("Owen",25,90,"class05"));
list.add(new Student("Jim",30,80,"class05"));
list.add(new Student("Steve",28,66,"class06"));
list.add(new Student("Kevin",24,100,"class04"));
int allage=0;
double allscore =0;
for (int i = 0; i < list.size(); i++) {
allage = allage+list.get(i).age;
allscore = allscore+list.get(i).score;
}
int aveage = allage/list.size();
double avescore = allscore/list.size();
System.out.println(aveage);
System.out.println(avescore);
}
}
class Student{
String name;
int age;
double score;
String classNum;
public Student(String name, int age, double score, String classNum) {
super();
this.name = name;
this.age = age;
this.score = score;
this.classNum = classNum;
}
}