java: part i · •the name of the constructor is always the same as the classname •when we do...

Post on 24-Aug-2020

3 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Java: part IJef De Smedt

Beta VZW

You

• Name

• What kind of work do you do here?

• Experience with programming languages?

• Expectations

Course contents

• The Java language

• Java variables

• Selection and iteration

• Java classes

• Exceptions

• Working with Numbers and Strings in Java

• Inheritance and interfaces

• Collections

• Introduction to writing GUI(windows) programs

What is Java?

• Programming language

• Origin: • Sun microsystems (now Oracle), 1990

• Started as alternative to C/C++

• Named “Oak”

• Programming “smart appliances” (embedded systems)

• Write once => run everywhere (different appliances)

• First version: 1992

• First available download: 1994 (name => “Java”)

Java Technology: Java Virtual Machine

Source code Machine codeCompile

“Classical programming language” (e.g. C or C++)

(can be executed by computer)

Source code(.java) Bytecode (.class)

Javac(compile)

Java (and .NET languages)

(cannot be executed by computer butis “executed” by Java Virtual Machine)

Machine code

(can be executed by computer)

Java

Intermezzo: a “faulty” comparison

• Take an MS-Word document

• Take a compiled Java program

.docx“executed” (shown on

screen)

MS Word

.class executed

Java

Java technology: Java Virtual Machine

• Java Virtual Machine “controls” the execution of a Java program

• Important example: garbage collection• “classical programming language”: programmer has to free memory (if not:

memory leaks)

• Java programming language: programmer cannot free memory (Java Virtual Machines frees memory automatically)

Java technology: Object orientation

• Java is a strict Object Oriented programming language ( C++, Object Pascal, …)

• All code must be contained in a class

public class Hello {

public static void main(String[] args) {

System.out.println("Hello world");

}

}

Java technology: packages

• Package = namespace

• I write a library with a class Hello,you write a library with a class Hello => how can we make a differencebetween the two?

• Answer: change the name• org.betavzw.Hello (class Hello in package org.betavzw)• be.mypaymentsolution.Hello (class Hello in package be.mypaymentsolution)

• Package names use domain names by convention (unique)

• Directory structure must follow package structure: …\org\betavzw\Hello.java

Java: typesafe language

• A variable is used to “remember” a value

• Every variable must be declared before it can be used

• Declaring a variable: telling what the type of the variable is =>• How much memory does the variable need

• What can we do with it

Java: type int

• How many people are there in this room => whole number (integer)

• Declaration:int number;

• Declare and assign a value:int number = 12;

• Meaning of ‘+’:int number1=30, number2=12;

int sum = number1 + number2;

• (sum equals 42)

Java: type String

• What is your name => text (String)

• DeclarationString name;

• Declare and assign a value:String name = "nobody";

• Meaning of ‘+’:String prefix = "no", name="body“;String myname = prefix + name;

• (myname equals “nobody”)

Variable naming

• Java is case-sensitive: “Name” is not “name”

• Name of variable cannot start with a number

• Name of variable can contain characters, numbers, $ and underscore

• Name of variable cannot be a reserved Java word

• Name of variable cannot contain spaces

main method

• Every program needs a main-method <= starting point

• Most simple Java applicationpublic class MyFirstApp {

public static void main(String[] args) {

System.out.println(“Hello world”);

}

}

• The println method prints to the screen

Java is “freeformatted”

• This is the same program:public class MyFirstApp {public static void

main(String[] args) {System.out.println(“Hello

world”);}}

• It is a good idea to write one command (statement) per line

• Every statement is terminated by ;

• Braces like { and } denote code that belongs to one parent

Run java program

• First we have to compile it:javac MyFirstApp.java

• Then we can run it:java MyFirstApp

• With a package name:• Compile: javac org/betavzw/MyFirstApp.java

• Run: java org.betavzw.MyFirstApp

Java variables(javavar01)

//package of this class

package org.betavzw;

//We are using a class from a different package

import javax.swing.JOptionPane;

public class Main {

//Starting point of the application

public static void main(String[] args) {

//Shows a dialogscreen to ask for input

String name = JOptionPane.showInputDialog("What is your name");

System.out.println("Hi " + name);

}

}

Java variables(javavar02)

• The ‘+’ operator means different things for integers and strings (andthat rhymes!)

// '+' means 'add' because number1 and number2 are integers

int sum = number1 + number2;

// '+' means 'concatenate' here because it is used with Strings

System.out.println("The sum of " + number1 + " and " + number2 + " equals " + sum);

Java variables(javavar03)

• char is one character

• It is not the same as a String

//character is not the same as a string (single quotes)

char newline = '\n';

//We can also concatenate a String and a character

String text = "Hi, how" + newline + "are you?";

System.out.println(text);

Java selection(javaselection01)

• If-statement

public static void main(String[] args) {

int number = Integer.parseInt(JOptionPane.showInputDialog("Enter a positive number"));

if (number > 0) {

System.out.println("Well done!!!");

} else {

System.out.println("Not correct.");

}

}

Java selection(javaselection02) (Java 8)

• Multiple(nested) if

LocalDateTime time = LocalDateTime.now();

int hour = time.getHour();

if (hour < 12) {

System.out.println("Good morning");

} else if (hour == 12) {

System.out.println("hey, it's noon");

} else if (hour < 18) {

System.out.println("Good afternoon");

} else {

System.out.println("Good evening");

}

Java String equality(javaselection03)

• Using == on strings means testing on memory location

String name = JOptionPane.showInputDialog("What is your name?");

//Does this work?

if (name == "Stop") {

System.out.println("That is a strange name");

} else {

System.out.println("Hi " + name);

}

Java String equality(javaselection04)

• Use equals()-method to test String equality

if (name.equals("Stop")) {

System.out.println("That is a strange name");

} else {

System.out.println("Hi " + name);

}

Java String equality

• Two strings are “==“ equal when they are assigned to each other:

String testString = "test";

String testString2 = testString;

if (testString == testString2) {

System.out.println("These two strings refer to the same memory position, so '==' works");

} else {

System.out.println("This cannot be true");

}

Java String equality: exception

• Two constant strings are the same when they have the same value(there is only one “test” for Java)

testString = “test”;

testString2 = "test";

if (testString == testString2) {

System.out.println("It is still the same String for Java");

}else {

System.out.println("This cannot be true");

}

Java Switch case(javaselection05)

switch(age) {

case 12:

System.out.println("You are twelve");

break;

default:

System.out.println(“You are not twelve");

break;

}

Java switch case(javaselection06)

• Since Java 1.7 we can use switch case for Strings tooswitch(name) {

case "stop":case "Stop":

System.out.println("This is a strange name");break;

default:System.out.println("Hi " + name);break;

}

Java while (javaiteration01)

• While number less than 1 or (||) greater than 10 do something

while(number < 1 || number > 10) {

JOptionPane.showMessageDialog(null, "Please specify a number between 1 and 10");

number = Integer.parseInt(JOptionPane.showInputDialog("Give a number between 1 and 10"));

}

Java do while (javaiteration02)

//a do..while statement is executed at least once

int number;

do {

number = Integer.parseInt(JOptionPane.showInputDialog("Give a number between 1 and 10"));

if (number < 1 || number > 10) {

JOptionPane.showMessageDialog(null, "Please specify a number between 1 and 10");

}

}while (number < 1 || number > 10);

Java for (javaiteration03)

//We use a for-loop when we know on beforehand how many times a piece of code will be executed

for (int i=0; i< 5; i++) {

System.out.println("i equals " + i);

}

//this is the same

int i = 0;

while (i < 5) {

System.out.println(" i equals " + i);

i++; // do not forget this!!! (that is why we prefer a for-loop here)

}

Java for each (javaiteration04)

• Numbers is an array

for (int number: numbers) {

System.out.print(number + " ");

}

• Remark: the for each variable (i.e. number) is readonly

Java Classes

• A class is the declaration of a type

• A variable of a class type is called an object (hence “object orientedlanguage”)

• A class declares fields (private member variables)

• The values of the fields of an object is called “state”

• A class also declares methods

• Methods work on an object and change the state.

Java private fields (javaclass01)

• A person has a name and a birthdate

• Fields should be made inaccessible from the outside world(private)

public class Person {

//Fields not accessible outside the class

private String name;

private LocalDate birthdate;

Java getters and setters (javaclass01)

• We need (public) methodes to read and write the values of the fields

//Public getter() method to get the value of name

public String getName() {

return name;

}

//Public setter() method to set the value of name

public void setName(String name) {

// "name" refers to the argument of the method

//"this.name" refers to "private String name"

this.name = name;

}

Java object creation(javaclass01)

//declare variable (object) of type(class) Person

//and initialize by using the "new" operator and calling a constructor

Person p = new Person();

//Give a name to the person

p.setName("Elvis");

p.setBirthdate(LocalDate.of(1935, Month.JANUARY, 8));

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("d MMM Y");

System.out.println(p.getName() + " was born on " + p.getBirthdate().format(fmt));

Java implementation hiding(javaclass02)

• Fullname is calculated but we do not know that unless we look at the code

public class Person {private String firstname;private String lastname;…//public getter() method that returns a calculated valuepublic String getFullname() {

return firstname + " " + lastname;}

}

Java method overloading (javaclass03)

• We can have two methods with the same name, provided the argumentsare different

public void setBirthdate(LocalDate birthdate) {

this.birthdate = birthdate;

}

//Overloaded method (same name, different arguments)

public void setBirthdate(int year, int month, int day) {

this.birthdate = LocalDate.of(year, month, day);

}

Java method overloading(javaclass03)

• Different return value is not enough (=> error here)

public LocalDate getBirthdate() {

return birthdate;

}

/*public String getBirthdate() {

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("d/M/Y");

return birthdate.format(fmt);

}*/

Java constructor(javaclass04)

• The name of the constructor is always the same as the classname

• When we do not define a constructor, java generates a default (parameterless) constructor => we were able to writePerson p = new Person(); //Person() is a constructor

• A constructor is used to initialize an object.

• A constructor is the first method to be called on an object

Java constructor(javaclass04)

public class Person {private String name;private LocalDate birtdate;//When we do not define a constructor, Java generates a default

(empty) constructor//When we define our own constructor, the default constructor does

not existpublic Person(String name, LocalDate birtdate) {

this.name = name;this.birtdate = birtdate;

}

Java constructor(javaclass04)

• Using a constructorpublic static void main(String[] args) {

//Person p = new Person(); // not possible because default constructor does not exist

// When we create a person object, we have to give a name and a birthdate

Person p = new Person("Elvis", LocalDate.of(1935, 1, 8));System.out.println(p.getName() + " was born on " +

p.getBirtdate().toString());}

Java constructor overloading(javaclass05)

• We can call a constructor from within a constructor

public class Person {

public Person(String name) {

this.name = name;

birthdate = LocalDate.now(); // default birthdate

}

//Constructor overloading (same name, different arguments

public Person(String name, LocalDate birthDate) {

this(name); //calls public Person(String name)

this.birthdate = birthDate;

}

Java exceptions

• Exceptions are used to signalize an error

• Exceptions are part of the method signature• This method needs these arguments

• This method gives this return value

• This can go wrong with the method

• An exception cannot be ignored (program simply crashes)

• We can write code to handle the exception( catching an exception)

Java catch exception(javaexception01)

public static void main(String[] args) {

try {

int number = Integer.parseInt(JOptionPane.showInputDialog("Give a number: "));

System.out.println("The number is " + number);

} catch (NumberFormatException e) {

e.printStackTrace();

System.out.println("This is not a valid number");

}

System.out.println("When an exception is caught, the program continues.");

}

Java throw exception(javaexception02)

public void setBirthdate(LocalDate birthdate) throws IllegalArgumentException {

//"throws" is not necessary in the method declaration( in this case)

// because it a RuntimeExeption. But it is part

// of the documentation of the method => we mention it

if (LocalDate.now().compareTo(birthdate) < 0) throw new IllegalArgumentException("birthdate cannot be after today");

this.birthdate = birthdate;

}

Java throw exception(javaexception02)

• We do not catch the exception= >program crash

Person eve = new Person();

eve.setName("Eve");

eve.setBirthdate(LocalDate.of(2014,12, 31)); // this should throw an Exception

System.out.println(eve.getName() + " was born on " + eve.getBirthdate()); //not executed

Java period (javaexception03)

private class DatePeriod {

private LocalDate start;

private LocalDate end;

public DatePeriod(LocalDate start, LocalDate end) throws IllegalArgumentException{

if (start.compareTo(end) > 0) throw new IllegalArgumentException("Enddate should not be before start date");

this.start = start;

this.end = end;

}

Java BigDecimal(javanumbersandstrings01)

• BigDecimal is used for currency (float is not precise)

public static void main(String[] args) {

float f = 0.000000001F;

float f2 = f * 100000000;

System.out.println(f2); //0.0999999

BigDecimal bd = new BigDecimal("0.000000001");

BigDecimal bd2 = bd.multiply(new BigDecimal(100000000));

System.out.println(bd2);//0.1

}

Java StringBuilder(javanumbersandstrings02)

• Because a string is immutable it is better to use StringBuilder to build a string (hence the name probably)

public static void main(String[] args) {

String name = "Elvis Presley";

StringBuilder sb =new StringBuilder(name.length());

for(char c:name.toCharArray()) {

sb.insert(0, c);

}

System.out.println(sb.toString());

}

Java formatting (javanumbersandstrings03)

String s = String.format("Integer: %d", integer);

System.out.println(s);

System.out.printf("Integer with 5 digits: %05d\n", integer);

System.out.printf("Integer 5 characters wide(padded left): %5d\n", integer);

System.out.printf("Integer with right padding %-5d (followed by spaces)\n", integer);

System.out.printf("Positive (%5d) and negative (%5d) integers\n", integer, negatieveNumer);

Java formatting(javanumbersandstrings03)

System.out.printf("String: %s\n", name);

System.out.printf("Always 15 wide: %15s\n", name);

System.out.printf("5 chars at most: %.5s\n", name);

System.out.printf("PI with precision 7(rounded): %.7f\n", Math.PI);

System.out.printf("Napier number 10 characters wide, precision 7:%10.7f\n", Math.E);

System.out.printf("Hour and Minute: %1$tH:%1$tM\n", today);

System.out.printf("Day/Month/Year:%1$td/%1$tm/%1$tY\n", today);

System.out.printf("Day of week: %tA\n", today);

System.out.printf("Day of month: %tB\n", today);

Java regular expressions(javanumbersandstrings04)//The '.' character means any character. The '*' character means the previous character may occur 0

//or more times. => somewhere in the sentence must be the word Elvis

boolean matches = Pattern.matches(".*Elvis.*", "The singer Elvis Presley");

if (matches) {

System.out.println("\"The singer Elvis Presley\" contains \"Elvis\"");

} else{

System.out.println("Elvis has never entered the building");

}

Java regular expressions(javanumbersandstrings04)String bban = JOptionPane.showInputDialog("Give Belgian Bank Account number");

//[0-9] means one of the characters between 0 and 9. (we could also use \d for a digit) {3} means the previous character 3 times

matches = Pattern.matches("[0-9]{3}-[0-9]{7}-[0-9]{2}", bban);

if (matches) {

JOptionPane.showMessageDialog(null, "This is a valid account");

} else {

JOptionPane.showMessageDialog(null, "This is not a valid account");

}

Java regular expressions(javanumbersandstrings04)//A question mark means the previous character 0 or 1 timesPattern pattern = Pattern.compile("([0-3]?[0-9])/([0-1]?[0-9])/([0-9]{4})");Matcher matcher = pattern.matcher(date);if (matcher.matches()) {

//Because we have used brackets, we can extract the three groups that were surrounded by brackets

int day = Integer.parseInt(matcher.group(1));int month = Integer.parseInt(matcher.group(2));int year = Integer.parseInt(matcher.group(3));System.out.printf("We get the date %02d-%02d-%4d", day, month, year);

} else {

System.out.println("Sorry, no match");

}

Java inheritance(javainherit01)

• Every class in Java ultimately “inherits” from the class Object

• “Inherits” means that it automatically has all the methods from the base class

• So all methods that are defined in the class Object are available in allJava classes:• toString()

• equals()

• getClass()

• hashCode()

Java inheritance(javainherit01)

public class Person /*extends Object */ {

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Java inheritance(javainherit02)

• We use inheritance for an “is-a” relation between classes

• An Employee “is a” Person (with a department)

public class Employee extends Person{

private String department;

public String getDepartment() {

return department;

}

public void setDepartment(String department) {

this.department = department;

}

}

Java call base constructor(javainherit03)

public class Person {

private String name; //inaccessible to any other class

public String getName() {

return name;

}

public Person(String name) {

this.name = name;

}

}

Java call base constructor(javainherit03)

public class Employee extends Person {

private String department;

public String getDepartment() {

return department;

}

public Employee(String name, String department) {

//this.name = name; // name is private in Person => inaccessible

super(name); // calls contructor from Person

this.department = department;

}

}

Java method overriding(javainherit04)

• A subclass can change the implementation of base methods(overriding)

public class Person {

//method overriding

public String toString() {

return "My name is " + name;

}

}

Java polymorphism(javainherit05)

• Different classes => different implementations

public class Person {

//overrides toString() in Object

public String toString() {

return "The name of this person is " + name;

}

}

Java polymorphism(javainherit05)

public class Employee extends Person {

public Employee(String name) {

super(name);

}

//overrides toString() in Person

public String toString() {

return "The name of this employee is " + getName();

}

}

Java polymorphism(javainherit05)

public static void main(String[] args) {

Person[] persons = new Person[2];

persons[0] = new Person("Elvis");

persons[1] = new Employee("Priscilla");

for(Person p: persons) {

//When p is a Person the toString() method from Person is called

//When p is an Employee the toString() method from Employee is called

//==> polymorphism

System.out.println(p);

}

}

Java abstract class(javaabstract01)

• Sometimes we have no idea how to implement a method

Figure

getPerimeter()

Circle

getPerimeter()

Square

getPerimeter()

How can we calculate the perimeter when we do not know what kind of figure it is?

Java abstract class(javaabstract01)

public abstract class Figure { // a class with an abstract method must be abstract

private String name;

public Figure(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public abstract double getPerimeter(); // no implementation

}

Java abstract class (javaabstract01)

public class Circle extends Figure {

private double diameter;

public double getDiameter() {

return diameter;

}

public Circle(String name, double diameter) {

super(name);

this.diameter = diameter;

}

@Override

public double getPerimeter() {

return diameter * Math.PI;

}

}

Java abstract class(javaabstract01)

• Now we can handle squares and circles together as figures

public static void main(String[] args) {

Figure[] figures = new Figure[2];

figures[0] = new Square("Square One", 10);

figures[1] = new Circle("Circle One", 5);

for(Figure f : figures) {

System.out.printf("The perimeter of %s is %.2f\n", f.getName(), f.getPerimeter());

}

Java abstract class(javaabstract01)

• If we want to access the properties which are specific for squares or circles, we needcasting (and type checking)

for(Figure f : figures) {

if (f instanceof Square) {

double side = ((Square)f).getSide();

System.out.printf("The perimeter of %s with side %.2f is %.2f\n", f.getName(), side, f.getPerimeter());

}else {

double diameter = ((Circle)f).getDiameter();

System.out.printf("The perimeter of %s with diameter %.2f is %.2f\n", f.getName(), diameter, f.getPerimeter());

}

}

Java interface(javainterface01)

• Interfaces are super abstract classes => they have no implementation

• Interfaces often describe an ability of a class

• Ability really means that there are certain methods available

• E.g. when something can be located, it must have getXCoordinate() en getYCoordinate() methods

• A class can only inherit from one base class but it can implementmultiple interfaces

Java interface(javainterface01)

public interface Locatable {

int getXCoordinate();

int getYCoordinate();

}

public interface Movable extends Locatable {

void move(int x_dir, int y_dir);

}

Java interface(javainterface01)

public class House implements Locatable {private int x, y;public House(int x, int y) {

this.x = x;this.y = y;

}@Overridepublic int getXCoordinate() {

return x;}@Overridepublic int getYCoordinate() {

return y;}

@Overridepublic String toString(){

return "House";}

}

Java interface(javainterface01)

public class Car implements Movable {private int x, y;public Car(int x, int y) {

this.x = x;this.y = y;

}@Overridepublic int getXCoordinate() {

return x;}@Overridepublic int getYCoordinate() {

return y;}@Overridepublic void move(int x_dir, int y_dir) {

x+= x_dir;y+= y_dir;

}@Overridepublic String toString() {

return "Car";}

}

Java interface(javainterface01)

public static void main(String[] args) {

Locatable[] locatables = new Locatable[3];

Movable[] movables = new Movable[2];

locatables[0] = new House(50, 20);

Car c = new Car(20, 30);

locatables[1] = c;

movables[0] = c;

Person p = new Person(10,10);

locatables[2] = p;

movables[1] = p;

for(Movable m: movables) {

Move(m, 10, 10);

}

printPosition(locatables);

}

Java interface(javainterface01)

• We can write methods that work with locatables or movables

private static void Move (Movable m, int distX, int distY) {

m.move(distX, distY);

}

private static void printPosition(Locatable[] locs) {

for (Locatable l: locs) {

System.out.printf("%s (%d,%d)\n", l, l.getXCoordinate(), l.getYCoordinate());

}

}

Java interface versions(javainterface02): java8• What happens when we decide to change an interface (we try to avoid

that)• Two possibilities

• We give the new interface another name (Identifiable2)• (Java 8) we define default implementations in the interface

public interface Identifiable {String getName();default String getAddress() { // starting with Java 8

return "";}

}

Java interface versions(javainterface02): java8• Person can now work with the previous version of Identifiable (without address)

public class Person implements Identifiable{

private String name;

public Person(String name) {

this.name = name;

}

@Override

public String getName() {

return name;

}

}

Java interface versions(javainterface02): java8• p.getAddress() will return an empty string

public static void main(String[] args) {

Person p = new Person("Elvis");

System.out.println(p.getName() + " lives " + p.getAddress());

}

• Result: Elvis lives

• (but: address unknown)

Java collections

• Collections are classes that can contain multiple objects (compare toan array)

• Java collections are based on interfaces

Java collections: Collection interface

• Collection has the ability to hold a group of elements

• That means the ability to• Add a new element

• Remove an existing element

• Remove all elements (clear)

• Get the number of elements (size)

• Test whether the set is empty

• See whether the collection contains an element or not

• Traverse the elements (iterator)

Java collections(javacollection01)

public static void main(String[] args) {

Collection<String> building = new ArrayList<>();

building.add("Elvis");

if(building.contains("Elvis")) {

System.out.println("Elvis is in the building");

} else {

System.out.println("Elvis has left the building");

}

if (building.isEmpty()) {

System.out.println("The building is empty");

} else {

System.out.println("There is someone in the building");

}

Java iterator(javacollections01)

• An iterator has a method to determine if there is still another element(hasNext()), to advance and get the next element (next()) and to remove the current element (remove())

Iterator<String> it = building.iterator();

while (it.hasNext()) {

String name = it.next();

System.out.println(name);

}

//When a class has an iterator, we can use a for each

for (String s: building) {

System.out.println(s);

}

Java aggregate operations(javacollections02)

• Since Java 8 we can also traverse a set using a Stream and lambda expressions

• Let us say we have an Employee class:

public class Employee {private String name, department;public Employee(String name, String department) {

this.name = name;this.department = department;

}public String getName() {

return name;}public String getDepartment() {

return department;}

}

Java aggregate operations(javacollection02)

• We can traverse the list and print the employees from the accountintdepartment:

Collection<Employee> company = new ArrayList<Employee>();

company.add(new Employee("Elvis", "Entertainment"));

company.add(new Employee("Priscilla", "Accounting"));

company.add(new Employee("Colonel Parker", "Management"));

company.add(new Employee("Lisa Marie", "Accounting"));

company.stream()

.filter(e -> e.getDepartment().equals("Accounting"))

.forEach(e -> System.out.println(e.getName()));

Java lambda expressions

• The filter (and the foreach) functions expect a function

• This function is written as a lambda expression

(e -> e.getDepartment.equals(“Accounting”))

• means

function name( Employee e){

return e.getDepartment.equals(“Accounting”);

}

Java sets: (javacollection03)

• A set is a collection with unique valuespublic static void main(String[] args) {

Set<String> items = new HashSet<>();items.add("Elvis");boolean succeeded = items.add("Elvis"); // falseif (!succeeded) {

System.out.println("There is only one Elvis");}System.out.println("The set contains " + items.size() + " element");

}

Java sets (javacollection04)

• To find unique values, the equals() method is used.public class Employee {

private String name;public Employee(String name) {

this.name = name;}public String getName() {

return name;}

}

Java sets (java collection04)

• Two employees with the name “Elvis” are not equal:

public static void main(String[] args) {

Set<Employee> items = new HashSet<>();

items.add(new Employee("Elvis"));

boolean succeeded = items.add(new Employee("Elvis")); //true!!!

if (succeeded) {

System.out.println("There is an Elvis impersonator here");

}

Java sets (javacollection04)

• So we have to override the equals() method:@Overridepublic boolean equals(Object o) {

boolean equal = false;if (o instanceof Employee) {

Employee e = (Employee)o;equal = this.getName().equals(e.getName());

}return equal;

}

Java sets (javacollection04)

• But we use a HashSet so we also have to override the method tocalculate the hashcode.

• The hashcode is used to determine in which “bucket” the item shouldbe placed. In this case we use the hashCode from the name string

@Override

public int hashCode() {

return name.hashCode();

}

Java sets(javacollection4)

• There are different classes that implement Set:• HashSet : items are placed in buckets based on their hashCode (random

order) => very quick

• TreeSet: items are placed using a B-tree (ordered by value) => slower thanHashSet because of traversing the B-tree

• LinkedHashSet: hashtable with a linked list to order the items (insertion order) => almost as fast as a HashSet

Java list interface

• A list is an ordered collection (position capabilities)

• A list can contain the non-unique values

• A list has to ability to• Get an element by position in the list

• Set an element by an existing position in the list

• Get the position of the first occurence of an element

• Iterate over the list in reverse order (using a ListIterator instead of an Iterator) or starting from a certain position

Java list (javacollection05)

List<String> items = new ArrayList<>();items.add("Elvis"); // position 0items.add("Colonel Parker"); // position 1items.set(1, "Dries Van Kuijk"); // replace element 1items.add("Vernon");int index = items.indexOf("Elvis");System.out.println("Elvis is on position " + index);items.remove(1);String name = items.get(1); //Vernon is shifted to position 1System.out.println("On position 1 we have " + name);

Java ListIterator(javacollection05)

• Using a ListIterator we can iterate backward

ListIterator<String> it = items.listIterator(items.size()); //start at endwhile (it.hasPrevious()) {

System.out.println(it.previous());}

• Or using a for-loop

for(ListIterator<String> it = items.listIterator(items.size()); it.hasPrevious();) {

System.out.println(it.previous());

}

Java Map interface

• A Map is not a Collection (Collection contains single values)

• A Map holds key-value pairs

• The keys must be unique

• A key is connected to one value

• A map has to ability to• Put new key-value pairs in the map

• Get a value based on a key

• Check whether a key exists or not

• Check whether a value exists or not

Java Map (javacollection06)

String[] words = {"one", "two", "one", "three", "three", "one"};

Map<String, Integer> frequency = new HashMap<>();

for(String word: words) {

Integer freq = frequency.get(word);

if (freq == null) {

freq = 1;

} else {

freq = freq + 1;

}

frequency.put(word, freq);

}

System.out.println(frequency);

Java Swing

• The Swing classes are used to create a graphical user interface

• The class that represents the main window must be a JFrame. (or inherit from JFrame)

• JFrame contains a constructor with which we can set the title of the window

• A window also needs a size (setSize(Dimension))

• We also have to define what should happen when the user closes the window => exit the application

Java Swing(javaswing01)

public class Main{

public static void main(String[] args) {

JFrame w = new JFrame("First GUI app");

w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

w.setSize(new Dimension(300, 300));

w.setVisible(true);

}

}

Java swing(javaswing02)

• We start with a frame

JFrame w = new JFrame("First GUI app");

w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

w.setSize(new Dimension(600, 300));

w.setLocationRelativeTo(null); // center on screen

Java swing(javaswing02)

• Next we define two labels and a textfield

• We also define some sizes

JLabel lblName = new JLabel("Name: ");

JTextField txtName = new JTextField();

txtName.setPreferredSize(new Dimension(140,25));

JLabel lblResult = new JLabel();

lblResult.setPreferredSize(new Dimension(300,25));

Java swing(javaswing02)

• We create a button and add an actionlistener (what should happen when a user clicks the button)

JButton btnGreet = new JButton("Say hello");

btnGreet.setPreferredSize(new Dimension(120,25));

btnGreet.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String name = txtName.getText();

lblResult.setText(String.format("Hi %s", name));

}

});

Java swing border layout

• Borderlayout divides the component into 5 parts

Java swing(javaswing02)

• We add the components at the right position, pack the window soeach component gets its preferred size and show the JFrame

w.add(lblName, BorderLayout.WEST);

w.add(txtName, BorderLayout.CENTER);

w.add(btnGreet, BorderLayout.EAST);

w.add(lblResult, BorderLayout.SOUTH);

w.pack();

w.setVisible(true);

top related