ЛАБОРАТОРНАЯ РАБОТА №6
по дисциплине «Курсы Java Foundations и Java Programming»
Выполнил
студент
гр. 3530902/70201 _____________________ Медведева А.А.
подпись, дата
Проверил
_____________________ Нестеров С.А.
подпись, дата
Санкт-Петербург
2020
Выполнение задания
Задание 1
1. Recreate this class that was seen in the previous
package cell;
//класс из лекции для хранения внутри коллекции
//создание собственной коллекции на основе массива
System.out.println(cells.get(0));
System.out.println(cells.get(1));
cells.get(0).setValue("First Cell");
cells.get(1).setValue("Second Cell");
System.out.println(cells.get(0));
System.out.println(cells.get(1));
}//end method main
}//end class
4. We could try to create a generic collection similar to our non generic example.
Коллекция с использованием generic
package cell;
public T get(int i) {
return cells[i];
}//end method get
}
Задание 2
1. Create a project named classlist.
2. Сreate a class Student that has a main method.
3. Initialize an ArrayListof Strings called studentNames in the main method.
4. Create a static method named addStudents that adds each student in your
classroom to the ArrayList.
5. Call the addStudents method from main.
6. Create a static method named displayStudents that uses an enhanced for
loop to display the contents of the ArrayList. The output should look
like: Student Name: Mark
7. Call the displayStudents method at the end of main.
8. Collections contains a method called sort that takes in a List as a
parameter and lexicographically sorts the list. An ArrayListis a List so
use the Collections sort method on your ArrayListat the bottom of main.
9. Call the displayStudentsmethod again from main.
Результат работы:
Код программы:
package classlist;
//класс из лекции 3.2
//работа с ArrayList
import java.util.ArrayList;
import java.util.Collections;
Задание 3
1. Create a project named hashsetexample.
2. Create the following Coin class:
5. Create a number of coin objects that hold the following denominations (1, 2, 5, 10,
20, 50, 100)
6. Add the coins (1, 2, 5, 10, 20, 50) to the bagOfCoins HashSet. Do not add
coin100! Add coin10 to the HashSettwice!
7. Create a static method named findCointhat accepts the ArrayListand a coin object
as parameters and does not return any values. The method should be called from
main.
8. Use an if statement to check if the bag contains the coin that was passed as the
parameter. If the coin is in the bag then the following output should be displayed:
There is a coin10 in the bag otherwise There is no coin10 in the bag
9. Test it by using coin10 and coin100 for the search
10. Create a static method named displayBagContents that accepts the ArrayListas a
parameter and does not return any values. The method should be called from main.
Use an enhanced for loop to display the denomination value for the coins stored in the
HashSet.
11. Create a static method named displayBagDetailsthat accepts the ArrayListas a
parameter and does not return any values. If the HashSet is empty it should display a
message stating the bag is empty, otherwise display a how many coins are in the bag.
12. Identify the HashSet method that removes all of the elements from the set and
write it directly under the displayBagDetails() method call in main.
13. Call displayBagDetails() again, after you have removed all of the elements from
the set in main
Результат работы:
Код программы:
//Класс CoinTestDriver
package hashsetexample;
//класс из лекции 3.2 для проверки работы
//исследование HashSet
import java.util.HashSet;
public class CoinTestDriver {
//Class Coin
package hashsetexample;
//класс из лекции 3.2
//исследование HashSet
//класс для хранения внутри HashSet
public class Coin {
private int denomination;
Задание 4
Результат работы:
HashSet - A set similar to an ArrayList without any specific ordering.
List - An ordered Collection that may contain duplicates.
Collection - An interface used to define a group of objects. This includes lists and sets.
ArrayList - A list that is very similar to an array.
Set - A Collection of elements that does not contain any duplicates.
Задание 5
1. This activity uses the javabank project, open it in the IDE. You are going to update the
code to use an ArrayList instead of a static one dimensional array.
a. Open the javabank.java file.
b. Find the line that creates the static one-dimensional array named myAccounts
static AbstractBankAccount myAccounts[] = new
AbstractBankAccount[MAXACCOUNTS];
c. Comment out that line and create an ArrayList of AbstractBankAccount named
myAccounts directly underneath it.
//static AbstractBankAccount myAccounts[] = new
AbstractBankAccount[MAXACCOUNTS]; static ArrayList<AbstractBankAccount>
myAccounts = new ArrayList<AbstractBankAccount>();
myAccounts[noAccounts] = new CreditAccount(name,accountNum,balance);
becomes
myAccounts.add(new CreditAccount(name,accountNum,balance));
myAccounts[i].setBalance(myAccounts[i].getBalance()+deposit);
becomes
myAccounts.get(i).setBalance(myAccounts.get(i).getBalance()+deposit);
e. Run and test the java application by creating multiple accounts of various types and displaying
the
d. Identify all of the errors that now appear in the code and update them using the add() or get()
methods to work with the ArrayList.
Задание 6
Код программы:
package bikeproject;
import java.util.ArrayList;
import java.util.Random;
// класс, созданный по описанию из практики
//использование ArrayList для хранения Bike
public class BikeList {
fillArray(bikes);
displayStock(bikes);
displayBikeNumbers(bikes);
}
Задание 7
1. What is the difference between a set and a list?
Ответ: Лист может содержать несколько одинаковых элементов
2. You decide you want to roll 2 dice and see what the frequency is of each possible number
combination. Would you use a Set collection to do this? State your reason(s).
Ответ: Нет, так как set не может содержать одинаковых результатов выпадания
3. Using a collection create a variable that will store a list of countries (Strings). Your
collection should not store duplicates, and order is not important. Test your code by
adding 6 countries, one of which is a duplicate.
Ответ: HashSet <String> countries = new HashSet<>();
countries.add("Russia");
countries.add("Ukraine");
countries.add("Vietnam");
countries.add("USA");
countries.add("China");
countries.add("Russia");
for (String i:countries)
System.out.println(i);
4. Would the following Collection.sort() statements both work? Explain your answer.
HashSet<String> countriesSet = new HashSet<String>();
Collections.sort(countriesSet);
ArrayList<String> countriesList = new ArrayList();
Collections.sort(countriesList);
Ответ: HashSet нельзя сортировать.
Задание 8
1. Create a project named hashsetexample.
2. Create a HashMapExampleclass that includes a main method.
3. Initialize a HashMap named fruitBowlthat will hold 2 String values.
4. Create an AddElementsmethod that accepts the HashMap as a parameter and add an apple
using the put(Key,Value) function of the HashMap collection
5. Add the following fruits to the fruitBowl.
6. Create a displayElementsmethod that accepts the HashMap as a parameter and will be used
to display the values of the HashMap.
7. To simply check the contents of the HashMap you can include its name in an output
statement.
8. To format the output to suit your need you can use an enhanced for loop.
9. Add a red apple to the bottom of the add elements method to see that you lose the green
apple.
10.Create the following method that will check if the fruit exists in the bowl and then display its
value to screen or else display a fruit not found method.
Результат работы:
Код программы:
package hashmapexample;
//класс из лекции 3.3
//использование HashMap
import java.util.HashMap;
Задание 9
1. Create a project named lettersqueue.
2. Create a class named LettersQ.
3. Initialize a LinkedList of String named lettersQ.
4. Use the add method to add elements to the Stack.
5. Display the contents and size of the Queue.
6. Use a while loop to remove the first element from the Queue and display them to the
console while the Queue is not empty. Display the empty Queue after.
Результат работы:
Код программы:
package lettersqueue;
import java.util.LinkedList;
//класс из лекции
//очередь с использованием LinkedList;
public class LettersQ {
public static void main(String[] args) {
LinkedList<String> lettersQ = new LinkedList<String>();
lettersQ.add("A");
lettersQ.add("B");
lettersQ.add("C");
lettersQ.add("D");
// display the contents of the linked list
System.out.println("Linked list : " + lettersQ);
// display the size of the linked list
System.out.println("Queue Size: " + lettersQ.size());
while (!lettersQ.isEmpty()) {
System.out.println(lettersQ.removeFirst());
}
System.out.println("Linked list : " + lettersQ);
}
}
Задание 10
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:
Код программы:
package lettersqueue;
import java.util.LinkedList;
//класс из лекции
//стэк с использованием LinkedList;
public class LettersS {
public static void main(String[] args) {
LinkedList<String> letterStack = new LinkedList<String>();
letterStack.push("A");
letterStack.push("B");
letterStack.push("C");
letterStack.push("D");
Задание 11
1. Create a classlistobjproject.
2. Create a Student class that does not have a main method. It should have the following
instance fields and constructor
3. Create getters and setters for all of the instance fields
4. Create a toStringmethod that will return the value of the instance fields
5. Implement the Comparable interface in the Student class.
6. When the Comparable interface is implemented it forces the inclusion of compareTo()
method. This will be used for the Collections.sortmethod.
7. Create a driver class that will add students and then display them to screen.
8. Run and test your code to check that it works.
9. Update the code to sort the students by their mark.
10. To compare based on a primitive data type the valueOfmethod must be invoked. This
returns an Integer instance based on the value of the primitive. Update the code to use this
method
Результат работы:
Код программы:
package queueStackSort;
//класс из лекции
//сортировка и compareTo
//класс, который будет находиться в сортируемом массиве;
public class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int mark;
/* @Override
public int compareTo(Student arg0) { // метод, используемый внутри сортировок,
определяющий взаимное расположение элементов
//сортировка по фамилии
if (lastName.compareTo(arg0.getLastName()) < 0)
return -1;
if (lastName.compareTo(arg0.getLastName()) == 0)
return 0;
return 1;
} */
@Override
public int compareTo(Student stud2) //сортировка по оценке
{
if((Integer.valueOf(mark).compareTo(Integer.valueOf(stud2.getMark())) <
0 ))
return -1;
if((Integer.valueOf(mark).compareTo(Integer.valueOf(stud2.getMark())) ==
0 ))
return 0;
return 1;
}//end method compareTo
} //end class Student
Задание 12
Результат работы:
LinkedList - A double-ended queue; a queue that can add and remove elements to the
front or back of the list.
Nodes - The links of a LinkedList.
Collection - An interface used to define a group of objects. This includes lists and sets.
Maps that link a Key to a Value and may have duplicate Keys but cannot have duplicate Values.
LinkedList - A list of elements that is dynamically stored.
Queue - A list of elements with a first in first out ordering.
Задание 13
1. What is the difference between a Queue and a Stack? Give an example of each.
Ответ: Queue – FIFO {}->{a}->{a,b}->{a,b,c}->{b,c}->{c}->{}
Stack – FILO {}->{a}->{a,b}->{a,b,c}->{a,b}->{a}->{}
2.
Ответ:
package genericstack;
import java.util.ArrayList;
public T pop()
{
if (top==0)
{
new GenericStackException();
return null;
}
T i = items.remove(top-1);
top--;
return i;
}
public boolean isEmpty()
{
return top==0;
}
public static void main(String[] args)
{
GenericStack<Integer> s = new GenericStack<>();
for (int i=0; i<4; i++)
s.push(i);
for (int i=0; i<5; i++)
System.out.println(s.pop());
}
}
3. Is it possible to add nodes to the beginning of a LinkedList? If so, how? What about adding a
node to the end of a LinkedList? If this can be done, what method would be used?
Ответ: Да, это осуществимо с помощью методов add() и addLast()
4. What is the purpose of implementing the Comparable interface in one of our classes?
Ответ: Comparable interface имеет метод compareTo, который используется некоторыми
методами, такими как сортировка.
5.
Код программы:
Задание 14
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:
Код программы:
Задание 15
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:
Код программы: