Skip to content
Snippets Groups Projects
Commit ef38a3b4 authored by Anders's avatar Anders
Browse files

gjesp

parent 753bab5c
No related branches found
No related tags found
No related merge requests found
package lecture5.objects;
public class Book {
public class Book implements Comparable<Book>{
String title;
String author;
......@@ -14,8 +14,29 @@ public class Book {
return String.format("%s - %s", this.title, this.author);
}
public boolean equals(Object obj){
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof Book){
Book toCompare = (Book)obj;
if(this.author.equals(toCompare.author) && this.title.equals(toCompare.title)) {
return true;
}
}
return false;
}
}
@Override
public int compareTo(Book arg0) {
int cmp = this.author.compareTo(arg0.author);
if(cmp == 0){
return this.title.compareTo(arg0.title);
}
else{
return cmp;
}
}
}
\ No newline at end of file
package lecture5.objects;
import java.util.Comparator;
public class CompareTitle implements Comparator<Book>{
@Override
public int compare(Book arg0, Book arg1) {
return arg0.title.compareTo(arg1.title);
}
}
package lecture5.objects;
import java.util.ArrayList;
import java.util.Collections;
public class Library {
......@@ -43,6 +44,17 @@ public class Library {
Book wanted = new Book("Hvordan være tøff", "Anders");
System.out.println(myBooks.hasBook(wanted));
myBooks.add(new Book("Dyr", "Tommy"));
myBooks.add(new Book("Klima", "Susanne"));
myBooks.add(new Book("Biler", "Ida"));
myBooks.add(new Book("Andre ting", "Anders"));
Collections.sort(myBooks.books);
System.out.println(myBooks.books);
Collections.sort(myBooks.books, new CompareTitle());
System.out.println(myBooks.books);
}
......
package lecture5.objects;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
public class UseCollections {
public static void main(String[] args) {
Collection<Integer> tall = getCollection(10);
System.out.println(tall);
Integer smallest = Collections.min(tall);
System.out.println(smallest);
ArrayList<Integer> listOfNumbers = new ArrayList<>(tall);
Collections.sort(listOfNumbers);
System.out.println(listOfNumbers);
int count = Collections.frequency(tall, smallest);
System.out.println(smallest + " occur " +count+ " times");
}
private static Collection<Integer> getCollection(int numElem){
ArrayList<Integer> list = new ArrayList<>();
Random rand = new Random();
for(int i=0; i<numElem; i++) {
list.add(rand.nextInt(10));
}
return list;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment