I am trying to build a simple generic class that uses generic objects in java. everything compiles fine, but when i run the code, it doesn't display the objects i passed to it.
Here is my code:
public class ListDriver {
public static void main(String[] args) {
List<String> glist = new List<String>(10);
glist.add("milk");
glist.add("eggs");
System.out.println("Grocery List" + glist.toString());
}
public class List<T> {
private T[] datastore;
private int size;
private int pos;
public List(int numElements) {
size = numElements;
pos = 0;
datastore = (T[]) new Object[size];
}
public void add(T element) {
datastore[pos] = element;
}
public String toString() {
String elements = "";
for (int i = 0; i < pos; ++i) {
elements += datastore[i] + "";
}
return elements;
}
}
}
You don't increment your pos variable, so you're always adding in the same place. Try
public void add(T element) {
datastore[pos++] = element;
}
Your add method always replaces the element in position 0 (zero). You forgot to increment pos (pos++;)
Related
Are there any cases in which getFirst() and getLast() show the same element when using the LinkedList provided by Collections?
I am parsing data to staging variables to be held; then I am storing these variables in a new object to be stored in my LinkedList using the add() method. However, when I am printing out statements, after every time an object is added to my LinkedList, by using the getFirst() and getLast() they are pointing to the same object?
Please see code below (please dont critic the code too much, I am only a beginner so I know it isn't pretty, but it recreates my problem)
public class Main {
public static void main(String[] args) {
Parse parse = new Parse();
parse.main();
}
}
import java.lang.reflect.Array;
public class Parse {
String[] input = {"1", "a",
"2", "b",
"3","c",
"4", "d"};
Object tempObject = new Object();
String tempLength;
String tempFilename;
int arrayIndex = 0;
public static ObjectList objectList = new ObjectList();
Parse(){
}
public void main() {
for (int i = 0; i != input.length; i++) {
String stringInput = iterateInputArray(input, i);
addToTempObject(stringInput);
Object finalObject = new Object();
finalObject = tempObject;
Object tempObject = new Object();
objectList.addToList(finalObject);
System.out.println("First:" + ObjectList.listOfObjects.getFirst());
System.out.println("Last:" + ObjectList.listOfObjects.getLast());
}
}
public String iterateInputArray(String[] input, int arrayIndex){
String string = input[arrayIndex];
return string;
}
private void addToTempObject(String inputString){
if (tempLength == null){
tempLength = inputString;
tempObject.setLength(inputString);
}
else {
tempObject.setFilename(inputString);
tempFilename = inputString;
resetTempVariables();
}
}
private void resetTempVariables() {
tempLength = null;
tempFilename = null;
}
}
public class Object {
private String length;
private String filename;
public Object( String length, String filename) {
this.length = length;
this.filename = filename;
}
public Object(){
this.length = null;
this.filename = null;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setLength(String length) {
this.length = length;
}
public String getLength() {
return this.length;
}
public String getFilename() {
return this.filename;
}
}
import java.util.LinkedList;
public class ObjectList extends Object {
public static LinkedList<java.lang.Object> listOfObjects = new
LinkedList<java.lang.Object>();
public ObjectList() {
}
public void addToList(Object object){
listOfObjects.add(object);
}
}
I reduced the code. The reduced code is, for the discussion of the prorblem, identical to the provided code:
import java.util.LinkedList;
class Scratch {
public static final Object tempObject = new Object();
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
The code keeps adding one and the same object (tempObject) to the list. Notice the final keyword introduced to highlight that variable tempObject references the same object over its whole lifetime. Thus, the size of the list grows, but the list contains the same object, over and over again. This is why getFirst() and getLast() return the same object.
The problem can be fixed by, e.g., moving the declaration of tempObject in the loop:
import java.util.LinkedList;
class Scratch {
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
for (int i = 0; i != 10; i++) {
final Object tempObject = new Object();
list.add(tempObject);
System.out.printf("First: %s, Last: %s, Size: %d%n",
list.getFirst(),
list.getLast(),
list.size());
}
}
}
Ideone demo
yes, a linked list with one element. like following test
import static org.assertj.core.api.Assertions.assertThat
class ListSpec extends Specification{
def "linked list with one elem"(){
given: "a linked list with one element"
LinkedList<String> list = new LinkedList<>()
list.add("test")
expect:"last and first element are same"
assertThat(list.getFirst()).isEqualTo(list.getLast())
}
}
I am trying to figure out how to store the values of tst.insert() and tsttxt.insert() into an array. So far the only thing I have been able to do is have the program recognize that they are there. When I try to print the variables I get the last value of tst.insert(). I am assuming that the last value is displayed because the other values are being overridden.
public class genericdrive {
public static void main(String[] args) {
collection<Integer> tst = new collection<>();
collection<String> tsttxt = new collection<>();
//System.out.println("If collection is empty return true: " + tst.isEmpty());
tst.insert(45);
tst.insert(43);
tst.insert(90);
tsttxt.insert("Jeff");
tsttxt.insert("Rey");
}
}
..
public class collection<T> extends genericdrive {
private T element;
private T[]array;
// collection<T> objt = new collection<>();
public void set(T element) {
this.element = element;
}
public T get() {
return element;
}
public <T> void insert(T i) {
i = (T) element;
//array[0]=<T> i;
}
}
considering that array variable holds all the elements the insert function you wrote does not push any value into it.
It is a workaround if the private variable is expected to be an array.
Try the following:
public class MyCollection<T> {
private T element;
private T[] array;
MyCollection(){
array = (T[]) Array.newInstance( Comparable.class , 0);
}
public void set(T element) {
this.element = element;
}
public T get() {
return element;
}
public void insert(T i) {
T[] temp = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + 1);
temp[array.length] = i;
System.arraycopy(array, 0, temp, 0, array.length);
array = temp;
}
}
I am trying to fill UCFCourse courseOne in my constructor with a courses[] object in fillWithCourses().UCFCourse courseOne does populate outside of the constructor but will not go into it.
public class UCFSemester<courses> {
private static UCFCourse courseOne;
private static double totalSemesters;
private static double completionTime;
static boolean fillSemester = true;
public UCFSemester(UCFCourse courseOne, UCFCourse[] coursetwo) {
this.courseOne = courseOne;
}
public static UCFCourse getcourseOne() {
return courseOne;
}
public static void setCoursesone(UCFCourse courses) {
courseOne = courses;
}
public static void fillWithCourses(UCFCourse courses[], int l) {
int x = 0;
while (fillSemester) {
for (int n = 0; n < 5; n++) {
if (x != n && courses[x].getCourseLevel() < courses[n].getCourseLevel()) {
setCoursesone(courses[x]);
}
}
fillSemester = false;
}
}
}
Side question.How can I access this all in a non-static way?I need the entire thing to be non-static but no matter what I do I can't get it.Thanks!
You can simply do it by creating a List like this:
public class UCFSemester {
private List<UCFCourse> courseList = new ArrayList<>();
public UCFCourse getCourse(int index) {
return courseList.get(index);
}
public void addCourses(UCFCourse[] courses) {
for(int x = 0; x < courses.length; x++) {
courseList.add(courses[x]);
}
}
}
Here, I'm assuming that you are passing the UCFCourse[] array with all the course details that are there in that particular semester.
addCourses() function will take this array and then add all the corresponding courses to the List.
getCourse() function will return you any particular course from the List (Using Index). You can also modify the search in any way you want.
I have basic understanding of how to apply Mockito framework.
But when it comes to some real time scenarios I failed to write tests in Isolation(by Mocking the dependent classes).
Can you help me to write Unit test for PriorityQueuePrinter class by Mocking PriorityQueue Implementation(BinaryMaxHeap.java).
I wrote testPriorityQueue() with BinaryMaxHeap object, in this case my test becomes success but I want to achieve the same to mock BinaryMaxHeap so that my test will be Isolate. I think I have to set method behaviours also in my test method.
In short, Priority Queue is the Implementation for BinaryHeapTree and Printer class uses Priority Queue.
Below are the code classes.
public interface PriorityQueue<T extends Comparable<T>> {
int size();
void insert(T element);
T popMax();
}
public class BinaryMaxHeap<T extends Comparable<T>> implements PriorityQueue<T> {
private ArrayList<T> items;
public BinaryMaxHeap() {
items = new ArrayList<T>();
}
public int size() {
return items.size();
}
public void insert(T element) {
items.add(element);
shiftUp();
}
public T popMax() {
if (items.size() == 1) {
return items.remove(0);
}
T hold = items.get(0);
items.set(0, items.remove(items.size()-1));
shiftDown();
return hold;
}
/*
* place newly added element in correct position in binary tree
*/
private void shiftUp() {
int k = items.size() - 1;
while (k > 0) {
int p = (k-1) / 2; // get parent element index
T child = items.get(k);
T parent = items.get(p);
if (child.compareTo(parent) > 0) {
// parent and child are not in correct position, need to swap
items.set(k, parent);
items.set(p, child);
k = p;
} else {
break;
}
}
}
private void shiftDown() {
int k = 0;
int l = 2*k+1; // left leaf node
while (l < items.size()) {
int max = l; // assume left node as max element
int r = l+1; // right leaf node
if (r < items.size()) {
if (items.get(r).compareTo(items.get(l)) > 0) {
max++; // identify max element in leaf nodes
}
}
T parent = items.get(k);
T child = items.get(max);
if (parent.compareTo(child) < 0) {
// parent element is less than leaf node, need to swap it
T temp = items.get(k);
items.set(k, items.get(max));
items.set(max, temp);
k = max;
l = 2*k+1;
} else {
break;
}
}
}
}
public interface Printer {
public <T extends Comparable<T>> String asSortedString(T... values);
}
public class PriorityQueuePrinter implements Printer {
private PriorityQueue priorityQueue = null;
public <T extends Comparable<T>> PriorityQueuePrinter(PriorityQueue<T> priorityQueue) {
this.priorityQueue = priorityQueue;
}
public <T extends Comparable<T>> String asSortedString(T... values) {
//PriorityQueue<T> priorityQueue =
addElements(values);
//return getSortedElements();
return null;
}
private <T extends Comparable<T>> void addElements(T... values) {
//PriorityQueue<T> priorityQueue = new BinaryMaxHeap<T>();
for (T element : values) {
priorityQueue.insert(element);
}
//return priorityQueue;
}
public int size() {
return priorityQueue.size();
}
private String getSortedElements() {
StringBuilder sortedElements = new StringBuilder();
boolean isFirstElement = true;
while(priorityQueue.size() > 0) {
if (!isFirstElement) {
sortedElements.append(",");
}
isFirstElement = false;
sortedElements.append(priorityQueue.popMax());
}
return sortedElements.toString();
}
public static void main(String a[]) {
PriorityQueuePrinter p = new PriorityQueuePrinter(new BinaryMaxHeap<Integer>());
String sortedElements = p.asSortedString(1,4,6,3,2);
System.out.println(sortedElements);
}
}
Below is the sample test code tried but not able to complete.
public class PrinterTest {
#Mock
PriorityQueue<Integer> mockPriorityQueue; // mock object
PriorityQueue<Integer> priorityQueue;
#Test
public void testPriorityQueueWithMock() {
PriorityQueuePrinter printer = new PriorityQueuePrinter(mockPriorityQueue);
String s = printer.asSortedString(5,3,6);
assertEquals("6,5,3", s);
}
#Ignore
public void testPriorityQueue() {
priorityQueue = new BinaryMaxHeap<Integer>();
PriorityQueuePrinter printer = new PriorityQueuePrinter(priorityQueue);
String s = printer.asSortedString(5,3,6);
assertEquals("6,5,3", s);
}
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#After
public void tearDown() throws Exception {
System.out.println("==tearDown==");
}
}
#Before
public void setUp() throws Exception {
//mockPriorityQueue = new BinaryMaxHeap<Integer>();
MockitoAnnotations.initMocks(this);
}
}
So I am a college student just looking for a little help and understanding, I have a professor that does not allow us to use java pre-written classes such as ArrayList, so I am trying to figure out how to modify my current encapsulated array class to use generics so that I don't have to do so much casting in the application class of my program
public class ArrayClass {
private Object[] objArray;
private int index = 0;
public static final int MAX_SIZE = 100;
public ArrayClass(){
objArray = new Object[100];
}
public ArrayClass(int numSlots){
objArray = new Object[numSlots];
}
public ArrayClass(Object[] anArray, int newIndex){
objArray = new Object[newIndex];
for(int i=0; i<newIndex; i++){
objArray[i] = anArray[i];
}
index = newIndex;
}
//return object array, accessor
public Object[] getstrArr(){
return objArray;
}
//return # of actual data in array, accessor
public int getIndex(){
return index;
}
//return an object at given pos, accesor
public Object getObject(int pos){
return objArray[pos];
}
//assign a new object array, mutator
public void setObjArr(Object[] aStrArr){
for(int i=0; i<index; i++){
objArray[i] = aStrArr[i];
}
}
//assign a new index, mutator
public void setIndex(int anIndex){
index = anIndex;
}
//insert a new string into the array if there is room, increment index
public void add(Object someObj){
if(index < objArray.length){
objArray[index] = someObj;
index++;
}
}
//return the string with contents of array
public String toString(){
String output = " ";
for(int i=0; i<index; i++){
output = output + objArray[i].toString();
}
return output;
}
//return true if calling object is equivalent to argument
public boolean equals(Object someObj){
for(int i=0; i< index; i++){
if(objArray[i].equals(someObj))
return true;
}
return false;
}
}
public class ArrayClass<E> {
// return object array, accessor
public <T> T[] getstrArr(T[] t) {<--This is done because arrays are covarant in nature
return (T[]) Arrays.copyOf(objArray, index, t.getClass());
}
// return an object at given pos, accesor
public E getObject(int pos) {<-- For single elements just return E with casting
return (E) objArray[pos];
}
Implementation Notes
Length checks should be considered for Arrays.copy of
You can read a nice article about generics
Well, i would not expose your index with methods like setIndex, etc. Not adding null element check too.
Anyway, I would make something like:
public class ArrayClass<E> {
...
private E[] elements;
private int index;
...
public ArrayClass() {
this.elements = (E[]) new Object[MAX_SIZE];
this.index = 0;
}
// this constructor substitutes the method setObjArr
public ArrayClass(E[] elements) {
this.elements = elements;
this.index = elements.length;
}
...
public void add(E element) {
if (needsToGrow()) {
duplicateArraySize();
}
this.elements[index++] = element;
}
private boolean needsToGrow() {
return index + 1 == elements.length;
}
private void duplicateArraySize() {
E[] extendedArray = (E[]) new Object[this.elements.length * 2];
System.arraycopy(elements, 0, extendedArray, 0, elements.length);
this.elements = extendedArray;
}
public E get(int index) {
return this.elements[index];
}
public int size() {
return this.index;
}
...
}
I would do it like that:
public class ArrayClass<T> {
public T[] objArray;
private int index = 0;
public static final int MAX_SIZE = 100;
#SuppressWarnings("unchecked")
public ArrayClass(Class<T> c) {
objArray = (T[]) Array.newInstance(c,MAX_SIZE);
}
}
and so on.
And then:
ArrayClass<String> myStringArray = new ArrayClass<String>(String.class);