Home > Java > javaTutorial > body text

A Java collection framework question with multiple problem-solving ideas

高洛峰
Release: 2017-01-23 16:57:17
Original
1664 people have browsed it

Question: There are 30 students in a class whose student IDs are 20070301-20070330. They all took the Java programming course. The scores of all students are given (random numbers can be generated, ranging from 60-100). Please write a program to assign this class to The scores of each student are printed out in order from low to high.

Requirements: Use List, Map, and Set to implement respectively. The printed information includes student number, name, and grades.

1. Use List collection to implement

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.Iterator; 
import java.util.LinkedList; 
import java.util.TreeMap; 
  
  
  
public class Test2{ 
    
  public static void main(String[] args){ 
      
    /* 此处用ArrayList实现 
     * 
     * ArrayList<Student>al=new ArrayList<Student>(); 
    for(int i=20070301,j=10;i<=20070330;i++,j++) 
    { 
      al.add(new Student(i,(int) (40*Math.random()+60), "同学"+j)); 
    } 
      
    //ArrayList排序借助Collections中的sort()方法实现。 
    Collections.sort(al, new Sortbygrade()); 
    for(Student sd:al) 
    System.out.println(sd); 
      
    */
      
    LinkedList<Student> lt=new LinkedList<Student>(); 
    for(int i=20070301,j=10;i<=20070330;i++,j++) 
    { 
      lt.add(new Student(i,(int) (40*Math.random()+60), "同学"+j)); 
    } 
      
    //对链表排序 
    Collections.sort(lt, new Sortbygrade()); 
    //输出链表 
    for(Student sd:lt) 
      System.out.println(sd); 
      
  } 
    
} 
  
  
  
//学生类 
class Student{ 
  int num,grade; 
  String name; 
    
  //构造函数 
  public Student(int num,int grade,String name){ 
      
    this.num=num; 
    this.name=name; 
    this.grade=grade; 
  } 
    
  //此处必须覆写 
  public String toString(){ 
//   System.out.println("hi"); 
    return "学号:"+this.num+"\t"+"姓名:"+this.name+"  "+"成绩:"+this.grade; 
  } 
    
} 
  
//创建一个比较器类 
class Sortbygrade implements Comparator<Student>{ 
  
  @Override
  public int compare(Student s1, Student s2) { 
      
    if(s1.grade>s2.grade) 
      return 1; 
    if(s1.grade<s2.grade) 
      return -1; 
    if(s1.grade==s2.grade) 
      return s1.name.compareTo(s2.name); 
    return 0;     
      
  } 
    
}
Copy after login

The output result is as shown in the figure:

一道Java集合框架题 多种解题思路

Summary of List collection framework:

1. The List collection is actually a dynamic array, and elements can be taken out directly through a for loop without iteration.
2. When outputting a List collection, the toString() method of the objects stored in the collection will be called by default, so it needs to be overridden in the class.
If you do not override the toString() method, you must use

for(int i=0;i<lt.size();i++)
{
  Student s=lt.get(i);
  System.out.println("学号:"+s.num+"  姓名:"+s.name+"  成绩:"+s.grade);
}
Copy after login

3. The sorting of the List collection requires the help of the Collections tool class, that is, Collections.Sort (list, new comparison device class()) method. Therefore, you need to customize a comparator class and define your own comparison rules.

2. Use Set collection to implement
(1) Use TreeSet to implement

package com.package1;
  
import java.util.*;
  
public class StuScore {
  
public static void main(String[] args) {
  
  TreeSet<Student> ts=new TreeSet<Student>(new Com());
  //添加元素进去
  for(int i=20070301,j=1;i<=20070330;i++,j++)
  {
    ts.add(new Student(i,"同学"+j,(int) (40*Math.random()+60)));
  }
  
  //迭代循环取出
  Iterator<Student> it=ts.iterator();
  while(it.hasNext())
  {
    Student o1=it.next();
    System.out.println("学号:"+o1.num+" "+"姓名:"+o1.name+" "+" "+"成绩:"+o1.grade);
  
  }
  
}
}
//学生类
class Student 
{
int num;
int grade;
String name;
  
  
public Student(int num, String name,int grade)
{
  this.num=num;
  this.name=name;
  this.grade=grade;
}
}
class Com implements Comparator
{
  
@Override
public int compare(Object o1, Object o2) {
  
  Student s1=(Student) o1;
  Student s2=(Student) o2;
  if(s1.grade>s2.grade)
    return 1;
  if(s1.grade<s2.grade)
    return -1;
  if(s1.grade==s2.grade)
  {
    return new Integer(s1.num).compareTo(new Integer(s2.num));
  }
  return 0;
}
}
Copy after login

The output result is:

Student ID: 20070307 Name: Classmate 16 Score: 60
Student ID: 20070309 Name: Classmate 18 Score: 60
Student ID: 20070314 Name: Classmate 23 Score: 61
Student ID: 20070318 Name: Classmate 27 Score: 61
Student ID: 20070322 Name: Classmate 31 Score: 61
Student ID: 20070306 Name: Classmate 15 Score: 62
Student ID: 20070310 Name: Classmate 19 Score: 64
Student ID: 20070302 Name: Classmate 11 Score: 66
Student ID: 20070308 Name: Classmate 17 Score: 68
Student ID: 20070321 Name: Classmate 30 Score: 68
Student ID :20070330 Name: Classmate 39 Score: 69
Student ID: 20070303 Name: Classmate 12 Score: 70
Student ID: 20070320 Name: Classmate 29 Score: 70
Student ID: 20070323 Name: Classmate 32 Score: 77
Student ID: 20070313 Name: Classmate 22 Score: 78
Student ID: 20070304 Name: Classmate 13 Score: 79
Student ID: 20070324 Name: Classmate 33 Score: 83
Student ID: 20070326 Name: Classmate 35 Score: 84
Student ID: 20070327 Name: Classmate 36 Score: 85
Student ID: 20070311 Name: Classmate 20 Score: 88
Student ID: 20070305 Name: Classmate 14 Score: 89
Student ID: 20070329 Name: Classmate 38 Score: 89
Student ID: 20070316 Name: Classmate 25 Score: 90
Student ID: 20070301 Name: Classmate 10 Score: 95
Student ID: 20070312 Name: Classmate 21 Score: 96
Student ID: 20070317 Name: Classmate 26 Score: 97
Student ID: 20070319 Name: Classmate 28 Score: 97
Student ID: 20070325 Name: Classmate 34 Score: 98
Student ID: 20070315 Name: Classmate 24 Score: 99
Student ID: 20070328 Name: Classmate 37 Score: 99

Summary of TreeSet:
1. Elements cannot be repeated, and TreeSet has sequential.
2. Two sorting methods:
(1) Customize a comparator class, such as class Com implementsComparator{ }, implement the compare(Object o1, Object o2) method, and define comparison rules in it.
(2) Let the elements themselves be comparative.
Steps: Implement the Comparable interface for the elements added into the TreeSet, and override the compareTo method. This order is also the natural order of elements, or called the default order.

The difference between method 1 and method 2:

Both methods have their own advantages and disadvantages. Using Comparable is simple. As long as the object that implements the Comparable interface directly becomes a comparable object, But the source code needs to be modified.

The advantage of using Comparator is that you do not need to modify the source code, but instead implement a comparator. When a custom object needs to be compared, just pass the comparator and the object together. The size can be compared, and in Comparator, users can implement complex and universal logic by themselves, so that it can match some relatively simple objects, which can save a lot of repeated work.

(2) Use HashSet to implement

package com.package1;
  
import java.util.*;
  
  
  
  
public class StuScore {
  
  public static void main(String[] args) {
      
    HashSet<Student> hs=new HashSet<Student>();
    //添加元素进去
    for(int i=20070301,j=1;i<=20070330;i++,j++)
    {
      
      hs.add(new Student(i,"同学"+j,(int) 
  
(40*Math.random()+60)));
    }
      
    ArrayList<Student>li=new ArrayList(hs);
      
    Collections.sort(li, new Sortbygrade());
      
    for(Student ss:li)
      System.out.println(ss);
      
  
  }
  
}
//学生类
class Student 
{
  int num;
  int grade;
  String name;
  
    
  public Student(int num, String name, int grade)
  {
    this.num=num;
    this.name=name;
    this.grade=grade;
  }
  public String toString(){
    //System.out.println("hi");
    return "学号:"+this.num+"\t"+"姓名:"+this.name
  
+"  "+"成绩:"+this.grade;
  }
    
    
}
  
  
class Sortbygrade implements Comparator{
  
  @Override
  public int compare(Object o1, Object o2) {
      
    Student s1=(Student) o1;
    Student s2=(Student) o2;
    if(s1.grade>s2.grade)
      return 1;
    if(s1.grade<s2.grade)
      return -1;
//   if(s1.grade==s2.grade)
      
    return 0;
  }
    
}
Copy after login

输出结果如下:
学号:20070310 姓名:同学19 成绩:60
学号:20070330 姓名:同学39 成绩:62
学号:20070326 姓名:同学35 成绩:63
学号:20070317 姓名:同学26 成绩:64
学号:20070318 姓名:同学27 成绩:65
学号:20070322 姓名:同学31 成绩:65
学号:20070301 姓名:同学10 成绩:67
学号:20070328 姓名:同学37 成绩:68
学号:20070304 姓名:同学13 成绩:68
学号:20070319 姓名:同学28 成绩:69
学号:20070313 姓名:同学22 成绩:70
学号:20070303 姓名:同学12 成绩:71
学号:20070312 姓名:同学21 成绩:71
学号:20070329 姓名:同学38 成绩:72
学号:20070306 姓名:同学15 成绩:72
学号:20070324 姓名:同学33 成绩:72
学号:20070305 姓名:同学14 成绩:75
学号:20070315 姓名:同学24 成绩:75
学号:20070314 姓名:同学23 成绩:78
学号:20070307 姓名:同学16 成绩:80
学号:20070311 姓名:同学20 成绩:81
学号:20070302 姓名:同学11 成绩:83
学号:20070309 姓名:同学18 成绩:84
学号:20070320 姓名:同学29 成绩:85
学号:20070321 姓名:同学30 成绩:85
学号:20070316 姓名:同学25 成绩:86
学号:20070327 姓名:同学36 成绩:90
学号:20070308 姓名:同学17 成绩:94
学号:20070323 姓名:同学32 成绩:94
学号:20070325 姓名:同学34 成绩:95

对HashSet的总结:
1、HashSet中的元素不可以重复,如果重复添加,则只会显示一个。
原理如下:
HashSet:底层数据结构是哈希表。是线程不安全的。不同步。
2、HashSet是如何保证元素唯一性的呢?
答:是通过元素的两个方法,hashCode和equals来完成。
如果元素的HashCode值相同,才会判断equals是否为true。如果元素的hashcode值不同,不会调用equals。
3、对HashSet的排序,通过将Set集合转化为List集合,借助Collections.Sort( )方法实现排序。

3、使用TreeMap来实现

package com.package1; 
  
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
  
public class TestTreeMap {
  
  public static void main(String[] args) {
    //1.创建集合
    TreeMap<Student,Integer> tm=new TreeMap<Student,Integer>();
    for(int i=20070301,j=10;i<=20070330;i++,j++)
    {
      int grade=(int) (40*Math.random()+60);
       //2、往集合对象中添加元素
       tm.put(new Student(grade,"同学"+j),i);
    }
      
    //3.遍历集合 ,排序完成 
    Set<Student> k=tm.keySet();
    Iterator<Student> it=k.iterator();
      
    while(it.hasNext()){
      Student key=it.next();
      Integer num=tm.get(key);
        
      System.out.println("学号:"+num+"  "+"姓名:"+key.name+"  "+"成绩:"+key.grade);
    }
  }
  
}
  
class Student implements Comparable<Student>{
  int grade;
  String name;
    
  public Student(int grade,String name){
    this.grade =grade;
    this.name=name;
  }
  
  @Override
  public int compareTo(Student o) {
      
    if(this.grade>o.grade) 
      return 1; 
      if(this.grade==o.grade) 
      { //当成绩相同时,按照姓名排序
       return this.name.compareTo(o.name); 
      } 
      return -1; 
  
  }
    
  
    
}
Copy after login

   

 输出结果为:

Student ID: 20070303 Name: Classmate 12 Score: 61
Student ID: 20070323 Name: Classmate 32 Score: 61
Student ID: 20070317 Name: Classmate 26 Score: 62
Student ID: 20070309 Name : Classmate 18 Score: 64
Student ID: 20070301 Name: Classmate 10 Score: 67
Student ID: 20070304 Name: Classmate 13 Score: 69
Student ID: 20070322 Name: Classmate 31 Score: 69
Student ID: 20070328 Name: Classmate 37 Score: 70
Student ID: 20070305 Name: Classmate 14 Score: 71
Student ID: 20070319 Name: Classmate 28 Score: 73
Student ID: 20070321 Name: Classmate 30 Score: 74
Student ID: 20070310 Name: Classmate 19 Score: 81
Student ID: 20070315 Name: Classmate 24 Score: 82
Student ID: 20070307 Name: Classmate 16 Score: 84
Number: 20070330 Name: Classmate 39 Score: 84
Student ID: 20070312 Name: Classmate 21 Score: 85
Student ID: 20070324 Name: Classmate 33 Score: 87
Student ID: 20070306 Name: Classmate 15 Score :88
Student ID: 20070308 Name: Classmate 17 Score: 90
Student ID: 20070327 Name: Classmate 36 Score: 90
Student ID: 20070318 Name: Classmate 27 Score: 91
Student ID: 20070316 Name: Classmate 25 Score: 92
Student ID: 20070320 Name: Classmate 29 Score: 92
Student ID: 20070314 Name: Classmate 23 Score: 93
Student ID: 20070313 Name: Classmate 22 Score: 94
Student ID: 20070302 Name: Classmate 11 Score: 95
Student ID: 20070325 Name: Classmate 34 Score: 95
Student ID: 20070329 Name: Classmate 38 Score: 97
Student ID: 20070326 Name : Classmate 35 Score: 98
Student ID: 20070311 Name: Classmate 20 Score: 99

Summary of TreeMap:
1. TreeMap sorts keys by default, so custom objects can be placed Enter the key and put the integer representing the student number into the value. When sorting by Key, you can specify a property in the custom object to sort.
2. The Map collection uses the put() method to add elements.
3. The principle of extracting Map collection: convert the map collection into a set collection. Take it out through the iterator. Two ways to retrieve the map set:
(1) Set keySet: Store all keys in the map into the Set collection. Because set has iterators. All keys can be retrieved iteratively, based on the get method. Get the value corresponding to each key.
(2) Set> entrySet: Store the mapping relationship in the map collection into the set collection, and the data type of this relationship is: Map.Entry

The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.

For more Java collection framework questions and multiple problem-solving ideas, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template