0% found this document useful (0 votes)
20 views17 pages

List Answer

The document provides a tutorial on Java data structures, specifically focusing on Lists, Arrays, ArrayLists, LinkedLists, Stacks, and Queues. It includes exercises for declaring and manipulating lists, using iterators, and implementing various list-related algorithms such as counting occurrences, sorting, and filtering unique words. Additionally, it outlines sample input-output scenarios for practical coding tasks involving lists and their functionalities.

Uploaded by

Raziq Ridzuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views17 pages

List Answer

The document provides a tutorial on Java data structures, specifically focusing on Lists, Arrays, ArrayLists, LinkedLists, Stacks, and Queues. It includes exercises for declaring and manipulating lists, using iterators, and implementing various list-related algorithms such as counting occurrences, sorting, and filtering unique words. Additionally, it outlines sample input-output scenarios for practical coding tasks involving lists and their functionalities.

Uploaded by

Raziq Ridzuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Sem 1 2024/2025 | TK1143

TK1143
TUTORIAL 7 (LIST)

Section A
1. Describe the differences between following Structure and when is the right time to use it
a) Array and ArrayList.

An Array is a fixed-size, basic structure for storing elements of the same type, while an
ArrayList is a resizable collection class in Java that can grow or shrink dynamically.
Arrays are better when size is known and performance is critical, but ArrayLists are more
flexible and easier to use due to built-in methods for adding or removing elements.

b) ArrayList and LinkedList

Both are part of Java's List interface. ArrayList uses a dynamic array internally, making
random access fast, but insertions and deletions slow because elements need to be
shifted. LinkedList, on the other hand, uses a doubly linked list, so insertions and
deletions are quicker at the cost of slower access. Choose ArrayList for frequent lookups
and LinkedList for frequent modifications.

c) Stack, Queue and List?

These are all ways to organize data. A Stack is a "last in, first out" (LIFO) structure, often
used for undo operations or recursive algorithms. A Queue is "first in, first out" (FIFO),
great for task scheduling. A List is more general, allowing indexed access. Use them
based on the specific order or access pattern you need.
Sem 1 2024/2025 | TK1143

2. Consider a following figure of myList elements with the specific index.

14 20 38 5 7
0 1 2 3 4

a) Write Java code to declare myList from type of integer.


ArrayList<Integer> myList = new ArrayList<>();

b) How many elements in myList?


0

c) Write Java code to add all the elements in myList


myList.add(14);
myList.add(20);
myList.add(38);
myList.add(5);
myList.add(7);

d) State an index of element 5.

e) Write Java code and illustrates the elements of myList after adding element 15 at
index 1.
myList.add(1, 15);

14, 15, 20, 38, 5, 7

f) Write Java code and illustrates the elements of myList after removing element 38
at index 2.
myList.remove(2);

14, 20, 5, 7
Sem 1 2024/2025 | TK1143

3. Consider the following Java code.

a) What is the name of the iterator used in the above code?


Iterator

b) What is the purpose of the iterator in the above code?


The first iterator, iterates through the myList to count the occurrences of the string
"Home". The second one, iterates through myNumbers to print all its elements.

c) Write the output of the code.

Number of Home in myList: 2

myNumbers list: 1 2 3 4 5 6 7 8
Sem 1 2024/2025 | TK1143

Section B
1. Based on the Class Person and PersonApp answer the following question.

Class Person

Class PersonApp
Sem 1 2024/2025 | TK1143

a) Can you explain class PersonApp code in line 15-18 ? What is the purpose of that
code?
This code sorts the persons list by age using a custom comparator. It compares the ages
of two Person objects and arranges them in ascending order.

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. Write a java program that read list of integer numbers from input user. If the number is
even add it into evenList. Otherwise add to oddList. At the end of the code, display the
elements of the odd and even numbers list respectively with ascending order. Display
your output in the following format:
< Odd or Even list> <Size_of_list in a bracket>: <the elements of the list that are separated by a space>
[Note: The code must use list and iterator]

Sample IO:
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
Sem 1 2024/2025 | TK1143

3. 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
Sem 1 2024/2025 | TK1143

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

Output Standard Output


Java Elements Looping
Data Structure List

Additional Function Trim and Remove all non-alphabetical characters

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. The I
school is also big. I like big school and go
big bus. to
school
by
bus
The
bus
is
big
The
school
is
Sem 1 2024/2025 | TK1143

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:

Add the word at the back of list

Display all words.

Basic Structure:
import java.util.*;

public class ListDemo {

public static void main(String[] args) {


List<String> myString = new ArrayList <String>();
Scanner in = new Scanner(System.in);

String passage = in.nextLine(); // read input passage


String delims = "\\W+"; // split any non-word
String [] words = passage.split(delims);
for (String str: words){

}
}
Sem 1 2024/2025 | TK1143

Full structure of worked-example program: List of Words.

1 import java.util.*;
2 public class MyList {
3 public static void main(String args[]){
4
5 List<String> list1 = new ArrayList <String>();
6 Scanner in = new Scanner(System.in);
7
8 String passage = in.nextLine(); // read input passage
9 String delims = "\\W+"; // split any non-word
10 String [] words = passage.split(delims);
11 for (String str: words){
12 //remove leading and trailing spaces
13 //add the word athe back of list
14 }
15 //display all word
16 }
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?

1. The list stores each word that were added to the list after splitting the passage by non-word
characters.
2. It represents each element or word from the split words array during the iteration.

3. myString.add(str); // line12-13

4. To print each word in the list.


Sem 1 2024/2025 | TK1143

LIST OF UNIQUE WORDS


Input Standard Input
Output Standard Output
Data Structure List

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 also I
big. I like big school and big bus. go
to
school
by
bus
The
is
big
also
like
and

1.for (String str : list1) {


if (str.equalsIgnoreCase(word)) { // Case-insensitive check for duplicate
return true; // Word is a duplicate
}
}

2. List of words-Contains all words from the input, including duplicates.


List of unique words-Contains only distinct words, removing any duplicates.

3. An iterator is used to traverse and check each word in the list efficiently.
Sem 1 2024/2025 | TK1143

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

Display the list.

Full structure of worked-example program: List of Unique Words.


1 import java.util.*;
2 public class MyList {
3
4 public static void main(String args[]) {
5
6 List<String> list1 = new ArrayList <String>();
7 boolean isDuplicate;
8 Scanner in = new Scanner(System.in);
9
10 String passage = in.nextLine(); // read input passage
11 String delims = "\\W+"; // split any non word
12 String [] words = passage.split(delims);
13
14 for (String str : words){
15 str = str.trim();
16 isDuplicate=false;
17 isDuplicate =CheckForDuplicates (list1, str);
18
19 if (!isDuplicate) {
20 //add new word into list and update the list size
21 }
22 }
23 // display all elements of list
24 }
25
26 static boolean CheckForDuplicates (List L1, String word) {
27 // check for duplicate words
28 // if found duplicate return true else return false
29 }
30 }

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.
Sem 1 2024/2025 | TK1143

LIST OF SORTED UNIQUE WORDS


Input Standard Input

Output Standard Output

JAVA Elements Selection, Looping,

Data Structure List

Problem Description
List of sorted words problem aims to display all words from a given passage in an ascending order. Your
task is to write a JAVA program for the List of Sorted Words.

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 also I
big. I like big school and big bus. The
also
and
big
bus
by
go
is
like
school
to
Sem 1 2024/2025 | TK1143

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

Display all word.

Full structure of worked-example program: List of Sorted Words.


1 import java.util.*;
2 public class MyList {
3 public static void main(String args[]) {
4 List<String> list1 = new ArrayList <String>();
5 Scanner in = new Scanner(System.in);
6 boolean isDuplicate;
7 int size=0;
8
9 String passage = in.nextLine(); // read input passage
10 String delims = "\\W+"; // split any non word
11 String [] words = passage.split(delims);
12 for (String str : words){
13 str = str.trim();
14 isDuplicate=false;
15 isDuplicate =CheckForDuplicates (list1, str);
16 if (!isDuplicate) {
17 //add new word into list and update the list size
18 }
19 //sort the list
20 }
21 displayList(list1, size);
22 }
23 static boolean CheckForDuplicates (List L1, String word) {
24 // check for duplicate words
25 // if found duplicate return true else return false
26 }
27
28 static void displayList(List l1, int s) {
29 // use the iterator to iterate list
30 // and display all elements
31 }
32 }//The Program Ends Here
33
Tutorial Activity:
1. State the differences between List of Unique Words and List of Sorted Words.
2. Name the method use to add new word into list.
3. Name the user defined functions used in List of Sorted Unique Words and its purpose.
4. Complete the CheckForDuplicates() and displayList() methods.
5. Write the statement to sort the list.
Sem 1 2024/2025 | TK1143

WORD FREQUENCIES
Input Standard Input

Output Standard Output

Data Structure List

Problem Description
Write a JAVA program that will display all words from a given passage with its frequencies. At the end of
output, print the text analysis such as (i) Total words, (ii) Number of Repeated words, (iii) Number of
Unique words and (iv) Most used word.

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 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. The I(2)
school is also big. I like big school and The(2)
big bus. also(1)
and(1)
big(4)
bus(3)
by(1)
go(1)
is(2)
like(1)
school(3)
to(1)
Sem 1 2024/2025 | TK1143

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

Display the list and text analysis


Sem 1 2024/2025 | TK1143

Class Data
** You must use class Data to complete question 4 in Section C for submission to CodeZinger
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 public String getWord() {
14 return word;
15 }
16
17 public void setWord(String newword) {
18 this.word= newword;
19 }
20
21 public int getFreq() {
22 return freq;
23 }
24
25 public void setFreq(int freq2) {
26 this.freq = freq2;
27 }
28
29 public static Comparator<Data> WordComparator = new Comparator<Data>()
30 {
31 // Used for sorting in ascending order of word
32 public int compare(Data a, Data b)
33 {
34 String word1 = a.getWord();
35 String word2 = b.getWord();
36
37 return (word1).compareTo(word2); //string1.compareTo(string2)
38 }
39 };
40 }
1. List of Unique Words-Contains only dis nct words from the input. Duplicate words are
removed and in no par cular order is enforced.

List of Sorted Words-Contains words, but they are sorted in a specific order. Sor ng is
typically done alphabe cally or based on ASCII values.
2. list1.add(str); // Adds the new word if it's not a duplicate
3. CheckForDuplicates -This method checks whether a given word already exists in the list. If
the word is found, it returns true (indica ng a duplicate), otherwise, it returns false.

displayList-This method uses an iterator to traverse through the list and print each word in
the list. It ensures the words are displayed in the sorted order.
4. Collec ons.sort(list1); // Sorts the list in ascending order based on ASCII values

You might also like