A simple Vector in Java that produces some tricky output - java

A very simple Vector in Java that produces the output that is somewhat difficult to follow. The code snippet is as show below.
package main;
import java.util.Vector;
final public class Main
{
public static void main(String[] args)
{
Vector<String> r = new Vector<String>();
r.addElement("O");
r.addElement("Y");
r.insertElementAt("A",0);
r.addElement("B");
r.addElement("F");
r.addElement("I");
r.addElement("X");
r.removeElement("F");
r.insertElementAt("G",3);
System.out.println(r);
}
}
The above simple Java code produces the output that is different than it actually appears to be. The actual output the above code produces is surprisingly, [A, O, Y, G, B, I, X]. Actually, it contains 9 elements. The output however, contains only 7 elements. How?

Did you notice that one of them was removeElement?

Actually you would have forget about the statement removeElement("F"). Since it is called it was removed and remaining elements alone shown. If you comment this line and try again, your expected result will come. Cheers up!!!

Related

Cannot clear java class from memory

I have a simple java class as shown below:
public class Add2Numbers
{
public static void main(String[] args)
{
int num1=2, num2=4, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
I compile the class and run in matlab using:
obj = Add2Numbers;
javaMethod('main', o,"");
and I get the output: Sum of these numbers: 6 which is, of course, correct.
Next I change the code in my text editor (e.g. set num1=4) compile, execute the clear statements below:
clear all
clear java
clear import
clear CLASSES
clear ALL
clear
then run again:
obj = Add2Numbers;
javaMethod('main', o,"");
But the calculation result remains the same as before. If I close and restart MATLAB the modified java class runs correctly. So how on earth do I clear a java class without having to close MATLAB and restart it?
set

Advice needed: What and how to removeNulls (I'm not sure exactly what to do)

I have a practice question from lectures which I am not sure how to solve and would appreciate insight into what should be done and an explanation:
Q: Give code for the method removeNulls(q) which removes from the Queue q all null elements. The method main contains a simple example illustrating the effect of method removeNulls.
package labsSGTsCoursework.cw1;
import net.datastructures.NodeQueue;
import net.datastructures.Queue;
public class CW1_q4 {
public static <E> void removeNulls( Queue<E> q) {
... // YOUR CODE REPLACES DOTS HERE
}
public static void main(String[] args) {
// test method removeNulls
Queue<Integer> que = new NodeQueue<Integer>();
que.enqueue(5);
que.enqueue(null);
que.enqueue(8);
que.enqueue(2);
que.enqueue(null);
System.out.println(que); // should print: "(5, null, 8, 2, null)"
removeNulls(que);
System.out.println(que); // should print: "(5, 8, 2)"
}
}
Sorry I did not notice it was a generic, so the markers approach will not work (thought is is a usefull trick sometimes so I leave it below).
Inside the method, make a new queue, copy all non null values from the old one to new, and then back to the original queue (as the values are consumed from orginal so you need to put them back).
For not, generic methods, the marker approach may work (as long as some values can never appearch in the input):
Insert a marker for example Integer.MAX_VALUE, iterate over the que and insert back all the elements which are not null, stop once you encounter your marker.

How do I run the same JUnit test multiple times with different test data each time?

I am just getting started with unit testing. I did the junit tutorial from a pdf from the tutorial points website. So my question is, I want to test my shunting yard algorithm and my RPNEvaluator.
The constructors (and any other variables to help you out with the context) look like this:
ShuntingYard.java:
private ArrayList<String> tokens = new ArrayList<String>();
public ShuntingYard(ArrayList<String> tokens) {
this.tokens = tokens;
}
RPNEvaluator.java:
private Queue<String> polishExpression;
public RPNEvaluator(Queue<String> exp) {
polishExpression = exp;
}
ShuntingYard.java has a method called toRpn() which will take an ArrayList and return a Queue after some processing.
RPNEvaluator has a method called evaluate which will take a Queue type and return a double after some processing.
With Junit I am trying to write some unit tests and I wanted to know if this start was the best way to go about it:
package testSuite;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
public class ExpressionEvaluationTest {
/**
* Initialise the lists to be used
*/
#Before
public void beforeTest() {
ArrayList<String> exprOne = new ArrayList<String>();
exprOne.add("3");
exprOne.add("+");
exprOne.add("4");
exprOne.add("*");
exprOne.add("2");
exprOne.add("/");
exprOne.add("(");
exprOne.add("1");
exprOne.add("-");
exprOne.add("5");
exprOne.add(")");
exprOne.add("^");
exprOne.add("2");
exprOne.add("^");
exprOne.add("3");
ArrayList<String> exprTwo = new ArrayList<String>();
exprTwo.add("80");
exprTwo.add("+");
exprTwo.add("2");
ArrayList<String> exprThree = new ArrayList<String>();
exprThree.add("2");
exprThree.add("/");
exprThree.add("1");
exprThree.add("*");
exprThree.add("4");
ArrayList<String> exprFour = new ArrayList<String>();
exprFour.add("11");
exprFour.add("-");
exprFour.add("(");
exprFour.add("2");
exprFour.add("*");
exprFour.add("4");
exprFour.add(")");
ArrayList<String> exprFive = new ArrayList<String>();
exprFive.add("120");
exprFive.add("/");
exprFive.add("(");
exprFive.add("10");
exprFive.add("*");
exprFive.add("4");
exprFive.add(")");
ArrayList<String> exprSix = new ArrayList<String>();
exprSix.add("600");
exprSix.add("*");
exprSix.add("2");
exprSix.add("+");
exprSix.add("20");
exprSix.add("/");
exprSix.add("4");
exprSix.add("*");
exprSix.add("(");
exprSix.add("5");
exprSix.add("-");
exprSix.add("3");
exprSix.add(")");
}
#Test
public void test() {
}
}
I was going to put this in the before() method:
ShuntingYard sy = new ShuntingYard(/arraylist here/);
And then in the test, pass the lists to the algorithm. My question is that I think I am going the long way around it, would it be better to have a parameterised annotation and pass those lists as a list of parameters?
and a further question: if a test for any of the ArrayLists passes then I am sure I can execute a subsequent test to the RPNEvaluator evaluate method. I hope I haven't been ambiguous.
Help would be very much appreciated.
I would come at it a little differently. Instead of just creating several sets of test data and calling the same test each time break it up in to something meaningful. Instead of writing one test called test() write several separate tests for each aspect of ShuntingYard. For example:
#Test public void
itDoesntDivideByZero()
{
ArrayList<String> divideByZeroExpression = Arrays.asList("5", "0", "/");
// Add code to call your method with this data here
// Add code to verify your results here
}
#Test public void
itCanAdd()
{
ArrayList<String> simpleAdditionExpression = Arrays.asList("1", "2", "+");
// Add code to call your method with this data here
// Add code to verify your results here
}
and so on. This will make your JUnit output much easier to read. When there's a failure you know that it failed while trying to add, or it failed while trying to evaluate an expression that would cause a divide by zero, etc. Doing it the way you have it in the original you'd only know that it failed in the test() method.
Each of the tests here does 3 things:
Arranges the test data
Performs some action with that data
Asserts that the results of the action are as expected
This Arrange, Assert, Act idiom is very common in automated testing. You may also see it called Given, When, Then as in, "Given these conditions, when I call this method, then I should get this result".
Try to get out of the mindset of writing one test to test an entire class or method. Write a test to test one part of a method. Consider this class:
public class Adder {
public int addOneTo(int someNumber) {
return someNumber + 1;
}
}
You might end up with a test suite that looks like:
#Test public void
itAddsOne()
{
int numberToAddTo = 1;
int result = new Adder().addOneTo(numberToAddTo);
assertEquals("One plus one is two", 2, result);
}
#Test(expected="NullPointerException.class") public void
itChokesOnNulls()
{
new Adder().addOneTo((Integer)null);
}
#Test public void
itDoesntOverflow()
{
int result = new Adder().addOneTo(Integer.MAX_VALUE);
// do whatever here to make sure it worked correctly
}
And so on.
The advise from Mike B is very good, try to separate your test thinking in one test per behavior/functionality.
For make your test more readable i probably write a static constructor for the class ShuntingYard that receives a string, then you can write:
ShuntingYard addition = ShuntingYard.createFromExpresion("2+2");
assertThat(addition.getRpn().evaluate(), is(4));
you can refactor a little more and ends with something like that:
assertThat(evaluate("2+2"), is(4))
That is easy to understand an and easy to read, and in addition write more test with diferent scenarios its one-line of code.
Other option its to write parametrized test, one example: http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/, but in my opinion are really ugly. This test are normally called "data driven test" and are used when you want to test the same code with different input values.
For this data-driven test a much better option its to use something like spock, a groovy framework for testing that allows you to write incredible semantic test, and of course you can use for testing java code, check this out: http://docs.spockframework.org/en/latest/data_driven_testing.html

Remove all 10s in a list and append a same number of 0s to the list at the end in JAVA

I've done most part of this. Anyone give me a small hint about how do I find the number of 10s in the list.
Eg. Input would be
[10,4,6,10,6,7]
Output must be
[4,6,6,7,0,0]
import java.util.ArrayList;
import java.util.List;
public class prob64 {
public static List output;
public static void getVal(List ll)
{
int count=0;
List ll1=new ArrayList();
for(int i=0;i<ll.size();i++)
{
if((int)ll.get(i)!=10)
{
ll1.add(ll.get(i));
}
if((int)ll.get(i)==10)
{
count++;
}
}
if(count>0)
{
ll1.add(8);
}
output=ll1;
System.out.println(output);
}
public static void main(String[] args) {
List<Integer> ll=new ArrayList();
ll.add(10);
ll.add(1);
ll.add(10);
ll.add(2);
prob64.getVal(ll);
}
}
The current output I'm getting is [1,2,0]. I'm supposed to get [1,2,0,0]
List.remove(Object) removes the first matching element. It also returns a boolean indicating if a removal was really done, so this should work :
while(ll.remove(10)) {
ll.add(0);
}
That is, as long as you find 10s to remove, add 0s. Note that List.add adds the element at the end of the list, which is your requirement (if I'm correct).
I suppose this is some kind of learning exercise, but I would advise you to find better names for your variable (ll & ll1 does not make your function easy to read).
You are adding only one zero at the end of the loop (in case 10s were found). You should count the number of 10s then add zeros as much as this number. Your program should look something like this:
int count=0;
List ll1=new ArrayList();
for(int i=0;i<ll.size();i++)
{
if((int)ll.get(i)!=10)
ll1.add(ll.get(i));
else
count++;
}
for(int j=0; j<count;j++)
ll1.add(0);
If count is number of 10's to add, use:
for(int j=0; j<count;j++){
ll1.add(8); // or ll1.add(0); ???
}
Few points to add to what others have mentioned above
I don't see any reason why you must define the output List to be static. When you define something(variables/functions) as static they are owned by the class rather that the objects and also it is a good programming practice not to change them using instance functions.What I mean is if you wish only to print there is no need of that output instance variable. You can directly print ll1.
Please use Generics in your code. When you know all you have in your list are integers specify it - Even in the function getVal(). I don't know how your code is compiling but you cannot cast Object to an int.
(int)ll.get(i)!=10
This code will fail. Try using Integer instead of int.
Your problem statement read replacing all 10's with 0's. So why are you adding 8 instead.It must be
ll1.add(0);
As other have specifies you need to add 0 as many time as your count is. So another loop is needed. Rest all look good.

Splitting Arrays- is my implementation correct?

I'm writing code for a hybrid data structure for school, and am debugging the code. Basically, this structure is a combination of a Double Linked List and an Array, where each list node contains an array of set size. Since this is an ordered structure, a provision has to be made to identify and split full arrays into equally into two nodes.
This is my code for splitting a node into two and then copying the latter half of the parent node's array values to the child node.
public Chunk<E> split(Chunk<E> node) {
Chunk<E> newChunk= new Chunk<E>();
newChunk.index= node.index++;
//connect to previous node
node.next= newChunk.next;
newChunk.prev= node.prev;
//connect to next node
newChunk.next= node.next.next;
node.next.prev= newChunk.prev;
//adds the latter half of the array contents to the new node
//and erases the same contents from the old node
for (int i=chunkSize/2; i<node.numUsed; i++) {
newChunk.items[i-chunkSize/2]= node.items[i];
node.items[i]=null;
}
//update capacity counter for both chunks
node.numUsed=chunkSize/2;
newChunk.numUsed= chunkSize/2;
return newChunk;
}
The toArray() method is returning null values from the list, so I think something is going on with this split method.
Questions I have are:
Are the linking of the new node to the rest of the list correct?
Is the the nulling of values inside the loop responsible for the null printout?
To answer this question thoroughly you should write some unit tests. For example:
package so3898131;
import static org.junit.Assert.*;
import org.junit.Test;
public class ChunkTest {
/** Ensure that the simplest possible case works as expected. */
#Test
public void testEmptySplit() {
Chunk<Object> old = new Chunk<Object>();
Chunk<Object> split = old.split(old);
assertEquals(0, split.chunkSize);
assertEquals(0, split.items.length);
assertEquals(0, split.index);
assertEquals(1, old.index);
}
#Test
public void testSplitWithOneItem() {
// TODO: make sure that after splitting one of the chunks contains
// one element, the other none.
}
#Test
public void testSplitWithTwoItems() {
// TODO: make sure that after splitting a chunk with two elements
// each of the new chunks contains exactly one of the elements.
// Use assertSame(..., ...) to check it.
}
}
This throws NullPointerExceptions at me because node.next may be null, in which case you cannot access node.next.next. This probably means that your code does not work. At least it does not work as I expect it.
Update: Your code is not correct. I wrote a unit test like this:
#Test
public void testSplitLinkage() {
Chunk<Object> old = new Chunk<Object>();
assertNull(old.prev);
assertNull(old.next);
Chunk<Object> split = old.split(old);
assertNull(old.prev);
assertSame(split, old.next);
assertSame(old, split.prev);
assertNull(split.next);
}
And then I modified the code so that this test runs successfully. I had to replace some lines with:
// connect to previous and next node
Chunk<E> one = node, two = newChunk, three = node.next;
one.next = two;
two.prev = one;
two.next = three;
if (three != null)
three.prev = two;
A better question would be: "How can I isolate (track down) the location of a bug in the source code by debugging?"
First you'll want to have a way to reproduce the problem. It appears you already have that. In a non-trivial code base, you will then want to do a binary search for the problem. Having two points A and B in program execution, where the program is in valid state in A, but not in B, choose a point C between A and B and check whether everything is correct at C. If it is, the bug is between C and B, else between A and C. Recurse until you have it narrowed down into a very small part of the code, where it is usually quite obvious.
This leaves the question of how verify whether execution was correct so far. There are various ways to do that, but it is probably most instructive to execute the program in a debugger, use a break point to suspend execution, and check that the variables contain the expected values.

Categories