Tutorial 8 - Answer
Tutorial 8 - Answer
Tutorial 8 - Answer
TUTORIAL 4 (LIST)
Section A
1. Describe the differences between following Structure and when is the right time to use it a) Array
and ArrayList.
Arrays are used when there is a need to use many variables of the same type. Meanwhile, ArrayList
provides constant time for search operation, so it is better to use ArrayList if searching is more
frequent operation than add and remove operation. The table below shows the differences between
Array and ArrayList.
Basis Array ArrayList
Initialization It is mandatory to provide the size of an array while We can create an instance of
initializing it directly or indirectly. ArrayList without specifying its size.
Java creates ArrayList of default size.
Iterating We use for loop or for each loop to iterate over an We use an iterator to iterate over
Values array. ArrayList.
Type-Safety We cannot use generics along with array because it is ArrayList allows us to store
not a convertible type of array. only generic/ type, that's why it is
type-safe.
Length Array provides a length variable which denotes the ArrayList provides the size() method
length of an array. to determine the size of ArrayList.
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to store the LinkedList internally uses a doubly linked list to store the
elements. elements.
3) An ArrayList class can act as a list only because it LinkedList class can act as a list and queue both because
implements List only. it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
5) The memory location for the elements of an The location for the elements of a linked list is not
ArrayList is contiguous. contagious.
6) Generally, when an ArrayList is initialized, a default There is no case of default capacity in a LinkedList. In
capacity of 10 is assigned to the ArrayList. LinkedList, an empty list is created when a LinkedList is
initialized.
7) To be precise, an ArrayList is a resizable array. LinkedList implements the doubly linked list of the list
interface.
14 20 38 5 7
0 1 2 3 4
e) Write Java code and illustrates the elements of myList after adding element 15 at index 1.
import java.util.*;
public class MyList {
public static void main(String[] args) {
List<Integer>myList = new ArrayList<Integer>();
myList.add(14);
f) Write Java code and illustrates the elements of myList after removing element 38 at index 2.
import java.util.*;
public class MyList {
public static void main(String[] args) {
List<Integer>myList = new ArrayList<Integer>();
myList.add(14);
myList.add(20);
myList.add(38);
myList.add(5);
myList.add(7);
//myList.add(1,15);
myList.remove(2);
System.out.print(myList);
14 20 5 7
0 1 2 3
myNumbers List:
1 2 3 4 5 6 7 8
Section B
1. Based on the Class Person and PersonApp answer the following question.
Class Person
Class PersonApp
a) Can you explain class PersonApp code in line 15-18 ? What is the purpose of that code?
From line 15-18, the class PersonApp use Collections.sort method to sort the persons by name and
age by doing comparison between the objects.
b)What is the output from this code?
[{name='Bulya', age=18}, {name='Mierza', age=19}, {name='Irdina', age=20},
{name='Muaz', age=20}, {name='Sharon', age=24}]
2. Please answer the question based on the full structure of worked-example program in reading
material : List of Words.
c) Named the method used to add new string into the list? Which line to indicate this process?
The add() method. For example, list1.add() . Use this method at line 12.
a) Discuss the different between the list of words and list of unique words.
List of words display all the words including the duplicate words while list of unique words shows
all the unique words without any duplicate words.
Iterator is used to iterate through all the elements of list1 one by one and do comparison between
word and the element in list1. If they are same, the word will not add into the list1. Otherwise, the
word will add into list1.
4. Please answer the question based on the full structure of worked-example program reading material :
List of Sorted Words.
1 import java.util.*; public class MyList {
a) State 2 public static void main(String args[]) {
the 3 List<String> list1 = new ArrayList <String>();
4 Scanner in = new
5 Scanner(System.in); boolean
6 isDuplicate; int size=0;
7
8 String passage = in.nextLine(); // read input passage
9 String delims = "\\W+"; // split any non
10 word String [] words =
11 passage.split(delims); for (String str :
12 words){ str = str.trim(); isDuplicate=false;
13 isDuplicate =CheckForDuplicates (list1, str);
14 if (!isDuplicate) {
15 //add new word into list and update the list size
16 }
17 //sort the list
18 }
19 displayList(list1, size);
20 }
21 static boolean CheckForDuplicates (List L1, String word) {
22 // check for duplicate words
23 // if found duplicate return true else return false
24 }
25
26 static void displayList(List l1, int s) {
27 // use the iterator to iterate list
28 // and display all elements
29 }
30 }//The Program Ends Here
31
32
33
differences between List of Unique Words and List of Sorted Words.
b) Name the user defined functions used in List of Sorted Unique Words and its purpose.
Input Output
2 3 0 -15 8 22 -11 6 -7 18 Odd List (4): -15 -11 -7 3
Even List (6): 0 2 6 8 18 22
Answer:
//BQ5
import java.util.*;
public class OddEvenList {
public static void main(String[] args) {
List<Integer> evenList = new ArrayList<Integer>();
List<Integer> oddList = new ArrayList<Integer>();
Scanner sc = new Scanner(System.in);
int e = 0;
int o = 0;
String n = sc.nextLine();
String [] numbers = n.split(" ");
Iterator it = oddList.iterator();
System.out.print("Odd List (" + o + "): ");
while(it.hasNext())
System.out.print(it.next() + " ");
}
6. Create a program that receives sequence of integers that ends with 0. For every non-repeating number add it
into NumberList. Display the size and all list elements. Then display all list elements again after composing
them in an ascending order. Follow the following output format.
<Size_of_list>: <the elements of the list that are separated by a space>.
[Note: The code must use list and iterator]
Sample IO:
Input Output
5 1 2 1 1 1 6 2 1 0 4: 5 1 2 6
4: 1 2 5 6
Section C :
There are four (4) questions given in this section. Your task is to write the program to implement data
structure List for each question.
LIST OF WORDS
Input Standard Input
Problem Description
The List of Words problem aims to display all words from a given passage. Your task is to write a Java program for
the List of words.
Input
Input of this program is a passage. A passage consists of N words and symbols. Symbols that will be considered in
the passage are full stop (.), comma (,), question mark (?) and exclamation mark (!).
Output
Output of the program is N lines, where each line contains a word.
Sample Input-Output
Input Output
I go to school by bus. The bus is big. I go
The school is also big. I like big school to
and big bus. schoo
l by
bus
The
bus
is
big
The
schoo
l is
also
big I
like
big
school
and
big
bus
Solution
The algorithm for List of Words:
Read a passage.
For all words in the passage:
Basic Structure:
import java.util.*;
}
}
Full structure of worked-example program: List of Words.
1 import java.util.*; public class MyList {
2 public static void main(String args[]){
3
4 List<String> list1 = new ArrayList <String>();
5 Scanner in = new Scanner(System.in);
6
7
String passage = in.nextLine(); // read input passage
8
String delims = "\\W+"; // split any non-
9
word String [] words =
10
passage.split(delims); for (String str:
11
words){
12
//remove leading and trailing spaces
13
//add the word athe back of list
14
}
15
//display all
16 word }
17
}
Tutorial Activity:
1. What is the purpose of list in the program?
2. What is the purpose of variable str?
3. Named the method used to add new string into the list? Which line to indicate this process?
4. What is the purpose of the statements in line 15 to 17?
Problem Description
List of Unique Words problem aims to display all words from a given passage in a non-recurring form.
Your task is to write a Java program for the List of Unique Words.
Input
Input of this program is a passage. A passage consists of N words and symbols. Symbols that will be
considered in the passage are full stop (.), comma (,), question mark (?) and exclamation mark (!). The
passage will have M unique words, where the M is less than or equal to N.
Output
Output of the program is M lines, where each line contains a unique word.
Sample Input-Output
Input Output
I go to school by bus. The bus is big. The school is I go
also big. I like big school and big bus. to
school
by bus
The is
big
also
like
and
Solution
The algorithm for List of Unique Words:
Read a passage
For all words in the passage:
Remove unnecessary characters
If the word not exist in list
Add the word at the back of list
Tutorial Activity:
1. Write the java code to show the if statement to check for duplicates word in the list.
2. Discuss the different between the list of words and list of unique words.
3. Specify the reason of using iterator in this problem.
Program Scope: Value of ‘A’ is smaller that ‘a’. Each character is based on the value of ASCII CODE, where
ASCII CODE of character ‘A’ is 65, and character ‘a’ is 97. This mean that the word “The” is greater than
word “also”.
Input
Input of this program is a passage. A passage consists of N words and symbols. Symbols that will be considered in
the passage are full stop (.), comma (,), question mark (?) and exclamation mark (!). The passage will have M unique
words, where the M is less than or equal to N.
Output
Output of the program is M lines, where each line contains a list of Sorted unique word.
Sample Input-Output
Input Output
I go to school by bus. The bus is big. The school is I The
also big. I like big school and big bus. also
and
big
bus by
go is
like
school
to
Solution
The algorithm for List of Sorted Words:
Read a passage
For all words in the passage:
If the word not exist in list
Add the word into the list
Sort the list
WORD FREQUENCIES
Input Standard Input
Output
Output of the program is M lines, where each line contains a word followed by symbol (, then followed by an
integer that represent the word frequency and ends by symbol). Display the analysis of Total words,
Number of repeated words, Number of unique words and Most used word as shown in Sample Input- Output.
Sample Input-Output
Input Output
I go to school by bus. The bus is big. I(2)
The school is also big. I like big school The(2)
and big bus. also(1)
and(1)
big(4)
bus(3)
by(1)
go(1)
is(2)
like(1)
school(3)
to(1)
Total words: 22
Number of repeated words: 6
Number of unique words: 12
Most used word: big
Solution
The algorithm for Words Frequencies:
Read a passage
For each word in the passage:
Search for the same word in the list
If not found:
Add the word into the list
Set and add the word’s frequency to 1
If found:
Update the word’s frequency value in list
Sort the list
1 import java.util.Comparator;
2
3 // Class Data
4 public class Data {
5 String word;
6 int freq;
7
8 public Data (String item){
9 this.word =item;
10 this.freq=1;
11 }
12
13
14 public String getWord() {
15 return word;
16 }
17
18 public void setWord(String newword) {
19 this.word= newword;
20 }
21
22 public int getFreq() {
23 return freq;
24 }
25
26 public void setFreq(int freq2) {
27 this.freq = freq2;
28 }
29
30
public static Comparator<Data> WordComparator = new Comparator<Data>()
31 {
32 // Used for sorting in ascending order of word
33 public int compare(Data a, Data b)
34 {
35 String word1 = a.getWord();
36 String word2 = b.getWord();
37
38
39 return (word1).compareTo(word2);
40 //string1.compareTo(string2) }
};
}