Implement a GENERIC Class named MagicBox Write a generic method to exchange the
ID: 3862047 • Letter: I
Question
Implement a GENERIC Class named MagicBox
Write a generic method to exchange the positions of two different elements in a list
Write a generic method that will count the occurrences of an item in the list
YOU MUST USE GENERICS!
Test your program with the following code
public class CountTest {
public static void main(String[] args) {
MagicBox occurances = new MagicBox();
String[] helloWorld = {"h", "e", "l", "l", "o", "w", "o", "r", "l", "d"};
int char_count = occurences.count(helloWorld, "l");
System.out.println("#occurrences of l: " + char_count);
Integer[] myints = {1, 9, 8, 8, 0, 0, 2, 0, 1, 7, 1, 0, 1, 0, 1, 0, 0};
int int_count = occurences.count(myints, 0);
System.out.println("#occurrences of zeros: " + int_count);
//before swap
System.out.println(helloWorld);
occurances.swap(helloWorld, 4,5);
//after swap
System.out.println(helloWorld);
//before int swap
System.out.println(myints);
occurances.swap(myints,7,8);
//after int swap
System.out.println(myints);
}
}
Explanation / Answer
CountTest.java
import java.util.Arrays;
public class CountTest {
public static void main(String[] args) {
MagicBox occurences = new MagicBox();
String[] helloWorld = {"h", "e", "l", "l", "o", "w", "o", "r", "l", "d"};
int char_count = occurences.count(helloWorld, "l");
System.out.println("#occurrences of l: " + char_count);
Integer[] myints = {1, 9, 8, 8, 0, 0, 2, 0, 1, 7, 1, 0, 1, 0, 1, 0, 0};
int int_count = occurences.count(myints, 0);
System.out.println("#occurrences of zeros: " + int_count);
//before swap
System.out.println(Arrays.toString(helloWorld));
occurences.swap(helloWorld, 4,5);
//after swap
System.out.println(Arrays.toString(helloWorld));
//before int swap
System.out.println(Arrays.toString(myints));
occurences.swap(myints,7,8);
//after int swap
System.out.println(Arrays.toString(myints));
}
}
MagicBox.java
public class MagicBox<T> {
public MagicBox() {
}
public int count(T t[], T c){
int count = 0;
for(int i=0; i<t.length; i++){
if(t[i] == c){
count++;
}
}
return count;
}
public void swap(T t[], int a, int b){
T temp = t[a];
t[a] = t[b];
t[b] = temp;
}
}
Output:
#occurrences of l: 3
#occurrences of zeros: 7
[h, e, l, l, o, w, o, r, l, d]
[h, e, l, l, w, o, o, r, l, d]
[1, 9, 8, 8, 0, 0, 2, 0, 1, 7, 1, 0, 1, 0, 1, 0, 0]
[1, 9, 8, 8, 0, 0, 2, 1, 0, 7, 1, 0, 1, 0, 1, 0, 0]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.