Set exercises

This is the end of the collection we talked about in our blog before. Let's do some exercises to end the collection.

Exercise 1:

Achieve as required:

  1. Encapsulate a news class, including the properties of the title and content, provide get and set methods, override the toString method, and print only the title when printing the object;
  2. Only one constructor with parameters is provided. When instantiating an object, only the title is initialized, and two objects are instantiated;

News 1: there are more than 10 million confirmed cases of covid-19, and millions of Hindu believers go to the Ganges river for "holy bath", which causes public concern

News 2: the man suddenly remembered that the fish he caught two months ago was still in the net. He picked it up and set it free as soon as possible

  1. Add the news object to the ArrayList set and traverse in reverse order;
  2. In the process of traversing the set, the news headlines are processed. If they exceed 15 words, only the first 15 are retained, and then "..." is added after them;
  3. Print and traverse the processed news headlines on the console.
public class Homework01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new News("The number of confirmed cases of covid-19 exceeded 10 million, and millions of Hindu believers went to the Ganges River\"Holy bath\"Cause public concern"));
        arrayList.add(new News("The man suddenly remembered that the fish he caught two months ago was still in the net, so he picked it up and set it free"));
        int size = arrayList.size();
        for (int i = size - 1;i>=0;i--){
            //System.out.println(arrayList.get(i));
            News news = (News)arrayList.get(i);
            System.out.println(processTitle(news.getTitle()));
        }
    }
    //Specially write a method to deal with and realize news headlines
    public static String processTitle(String title){
        if(title == null){
            return "";
        }
        if(title.length()>15){
            return title.substring(0,15)+"...";
        }else{
            return title;
        }
    }
}

class News{
    private String title;
    private String content;

    public News(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                '}';
    }
}

Exercise 2:

Use ArraryList to complete various operations on the object Car{name,price}

  1. Add: add a single element
  2. remove: delete the specified element
  3. contains: find whether the element exists
  4. size: get the number of elements
  5. isEmpty: judge whether it is empty
  6. Clear: clear
  7. addAll: add multiple elements
  8. containsAll: find whether multiple elements exist
  9. removeAll: delete multiple elements

To traverse all cars with enhanced for and iterators, you need to rewrite the toString method of car

public class Homework02 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        Car car = new Car("bmw",400000);
        Car car1 = new Car("Bentley",5000000);

        arrayList.add(car);
        arrayList.add(car1);
        System.out.println(arrayList);

        arrayList.remove(car);
        System.out.println(arrayList);

        System.out.println(arrayList.contains(car1));

        System.out.println(arrayList.size());

        System.out.println(arrayList.isEmpty());

        //arrayList.clear();

        arrayList.addAll(arrayList);
        System.out.println(arrayList);

        System.out.println(arrayList.containsAll(arrayList));

        //arrayList.removeAll(arrayList);

        System.out.println("=====enhance for======");
        for (Object o : arrayList) {
            System.out.println(o);
        }
        System.out.println("======iterator =====");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }

    }
}
class Car{
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

Exercise 3:

Complete the following tasks as required:

  1. Use the HashMap class to instantiate a Map type object m, and the key (String) and value (int) are used to store the employee's name and salary respectively. The stored data is as follows: jack-650 yuan; tom - 1200 yuan, smith - 2900 yuan;
  2. Change jack's salary to 2600 yuan;
  3. Raise the salary of all employees by 100 yuan;
  4. Traverse all employees in the set;
  5. Traverse all wages in the set;
public class Homework03 {
    public static void main(String[] args) {
        Map m = new HashMap();
        m.put("jack",650);
        m.put("tom",1200);
        m.put("smith",2900);

        System.out.println(m);
        m.put("jack",2600);//Replace, update
        System.out.println(m);

        //Raise the salary of all employees by 100 yuan;
        Set keySet = m.keySet();
        for (Object key : keySet) {
            //to update
            m.put(key,(Integer)m.get(key)+100);
        }
        System.out.println(m);

        System.out.println("=====ergodic=======");
        //Traverse Entry
        Set entrySet = m.entrySet();
        //iterator 
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            System.out.println(entry.getKey()+"-"+entry.getValue());
        }

        System.out.println("======Traverse all wages=====");
        Collection values = m.values();
        for (Object value : values) {
            System.out.println("wages="+value);
        }

    }
}

Exercise 4:

Try to analyze how HashSet and TreeSet achieve weight removal respectively?

  1. HashSet's de duplication mechanism: hashCode()+equals(), the bottom layer first stores the object and obtains a hash value through operation. The corresponding index is obtained through the hash value. If there is no data in the location of the table index, it is stored directly; If there is data, perform equals comparison [traversal comparison]. If it is different after comparison, add it, otherwise do not add it.
  2. TreeSet's de duplication mechanism: if you pass in a Comparator anonymous object, use the implemented compare de duplication. If the method returns 0, it is considered to be the same element / data, and it is not added. If you do not pass in a Comparator anonymous object, use the compareTo de duplication of the comparable interface implemented by the object you add.

Exercise 5:

Whether the following code will throw an exception and explain the reason from the source code level. [review reading source code + interface programming + dynamic binding]

TreeSet treeSet = new TreeSet();
treeSet.add(new Person());

class Person{}
Analyze source code:
add Method, because TreeSet() Constructor not passed in Comparator Anonymous inner class of interface
 So on the ground floor Comparable<? super K> k = (Comparable<? super K>) key;(Upward transformation)
Namely Person Turn into Comparable Type, not implemented Comparable So an exception will be thrown
public class Homework05 {
    public static void main(String[] args) {

        /*
            Analysis source code:
            add Method, because the TreeSet() constructor does not pass in the anonymous inner class of the Comparator interface
            So at the bottom, comparable<? super K> k = (Comparable<? super K>) key; (upward transformation)
            That is, turn Person into Comparable type, and no Comparable is implemented, so an exception will be thrown
         */
        TreeSet treeSet = new TreeSet();
        treeSet.add(new Person());
        System.out.println(treeSet);
        //Solution: the Person class implements the Comparable interface and rewrites the compareTo method
    }
}
class Person implements Comparable{
    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

Exercise 6:

Known: the Person class rewrites the hashCode and equals methods according to id and name. What does the following code output?

HashSet set = new HashSet();
Person1 p1 = new Person1(1001,"AA");
Person1 p2 = new Person1(1002,"BB");
set.add(p1);
set.add(p2);
p1.name = "CC";
set.remove(p1);
System.out.println(set);//2
set.add(new Person1(1001,"CC"));
System.out.println(set);//3
set.add(new Person1(1001,"AA"));
System.out.println(set);//4
  • Operation results
[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}]
[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='CC'}]
[Person1{id=1002, name='BB'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='CC'}, Person1{id=1001, name='AA'}]

Exercise 7:

Try to write a comparison between Vector and ArrayList?

Underlying structureeditionThread safe (synchronous) efficiencyExpansion multiple
ArrayListVariable arrayjdk1.2Unsafe and efficientIf there is a parameter structure, 1.5 times; If there is no parameter, expand the capacity by 10 for the first time and 1.5 times for the second time
VectorVariable array Object[]jdk1.0Safe and inefficientIf there is a parameter structure twice, if there is no parameter, expand the capacity by 10 for the first time, and expand the capacity by twice for the second time

Tags: Java Algorithm data structure set

Posted by Robkid on Tue, 09 Aug 2022 13:39:24 +0530