目录结构
对于使用ArrayList集合并使用Iterator遍历
package test2 ;
import java. util. ArrayList ;
import java. util. Iterator ;
public class T8 {
public static void main ( String [ ] args) {
ArrayList < String > arrayList = new ArrayList < > ( ) ;
arrayList. add ( "Java" ) ;
arrayList. add ( "Python" ) ;
arrayList. add ( "C++" ) ;
arrayList. add ( "JavaScript" ) ;
arrayList. add ( "Ruby" ) ;
arrayList. add ( "Swift" ) ;
arrayList. add ( "Kotlin" ) ;
arrayList. add ( "Go" ) ;
arrayList. add ( "Rust" ) ;
arrayList. add ( "TypeScript教程" ) ;
Iterator < String > iterator = arrayList. iterator ( ) ;
while ( iterator. hasNext ( ) ) {
String element = iterator. next ( ) ;
System . out. println ( element) ;
}
}
}
运行结果
在HashSet集合中添加Person对象
package test2 ;
import java. util. HashSet ;
class Person {
private String name;
private int age;
public Person ( String name, int age) {
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 int hashCode ( ) {
return name. hashCode ( ) ;
}
@Override
public boolean equals ( Object obj) {
if ( this == obj) return true ;
if ( obj == null || getClass ( ) != obj. getClass ( ) ) return false ;
Person person = ( Person ) obj;
return name. equals ( person. name) ;
}
}
public class T82 {
public static void main ( String [ ] args) {
HashSet < Person > personSet = new HashSet < > ( ) ;
personSet. add ( new Person ( "张三" , 25 ) ) ;
personSet. add ( new Person ( "李四" , 30 ) ) ;
personSet. add ( new Person ( "张三" , 25 ) ) ;
for ( Person person : personSet) {
System . out. println ( "Name: " + person. getName ( ) + ", Age: " + person. getAge ( ) ) ;
}
}
}
运行结果
使用TreeMap按学号的自然顺序的倒序打印键值对
package test2 ;
import java. util. * ;
public class T83 {
public static void main ( String [ ] args) {
TreeMap < Integer , String > studentMap = new TreeMap < > ( ) ;
studentMap. put ( 101 , "张三" ) ;
studentMap. put ( 103 , "李四" ) ;
studentMap. put ( 105 , "王五" ) ;
studentMap. put ( 102 , "贾六" ) ;
studentMap. put ( 104 , "吴七" ) ;
System . out. println ( "乱序输出:" ) ;
for ( Map. Entry < Integer , String > entry : studentMap. entrySet ( ) ) {
System . out. println ( "学号: " + entry. getKey ( ) + ", 姓名: " + entry. getValue ( ) ) ;
}
TreeMap < Integer , String > reverseStudentMap = new TreeMap < > ( Comparator . reverseOrder ( ) ) ;
reverseStudentMap. putAll ( studentMap) ;
System . out. println ( "\n倒序输出:" ) ;
for ( Map. Entry < Integer , String > entry : reverseStudentMap. entrySet ( ) ) {
System . out. println ( "学号: " + entry. getKey ( ) + ", 姓名: " + entry. getValue ( ) ) ;
}
}
}
运行结果