Java_Set练习
import java. util. HashSet ;
import java. util. Set ;
public class HM_Set1 {
public static void main ( String [ ] args) {
Set < Double > set = new HashSet < > ( ) ;
double [ ] arr = { 2.2 , 5.5 , 6.6 , 2.2 , 8.8 , 1.1 , 2.2 , 8.8 , 5.5 , 2.2 , 6.6 } ;
for ( double v : arr) {
set. add ( v) ;
}
System . out. println ( set) ;
}
}
import java. util. Random ;
import java. util. TreeSet ;
public class HM_TreeSet {
public static void main ( String [ ] args) {
Random random = new Random ( ) ;
TreeSet < Integer > treeSet = new TreeSet < > ( ) ;
int p = 0 ;
while ( treeSet. size ( ) < 8 )
{
int temp = random. nextInt ( 10 ) + 10 ;
System . out. println ( "第" + ( ++ p) + "次生成的随机数是:" + temp) ;
treeSet. add ( temp) ;
}
System . out. println ( "集合中保存的8个不重复的随机数是:" + treeSet) ;
}
}
import java. util. Iterator ;
import java. util. Scanner ;
import java. util. TreeSet ;
class book implements Comparable < book>
{
String name;
int price;
public book ( ) {
}
public book ( String name, int price) {
this . name = name;
this . price = price;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public int getPrice ( ) {
return price;
}
public void setPrice ( int price) {
this . price = price;
}
@Override
public String toString ( ) {
return "book{" +
"name='" + name + '\'' +
", price=" + price +
'}' ;
}
@Override
public int compareTo ( book o) {
return this . price - o. price;
}
}
public class HM_Books {
public static void main ( String [ ] args) {
Scanner scanner = new Scanner ( System . in) ;
TreeSet < book> treeSet = new TreeSet < > ( ) ;
int p = 0 ;
while ( true )
{
System . out. println ( "请输入第" + ( ++ p) + "本书的名称:" ) ;
String book_name = scanner. next ( ) ;
System . out. println ( "请输入第" + p+ "本书的价格(整数):" ) ;
int book_price = scanner. nextInt ( ) ;
treeSet. add ( new book ( book_name, book_price) ) ;
System . out. println ( "添加" + book_name+ "已经成功,继续添加请输入1,输入其他数字将结束!" ) ;
int key = scanner. nextInt ( ) ;
if ( key != 1 )
{
break ;
}
}
System . out. println ( "您一共添加了:" + p+ "本书,分别是:" ) ;
Iterator < book> it = treeSet. iterator ( ) ;
while ( it. hasNext ( ) )
{
System . out. println ( it. next ( ) ) ;
}
}
}