I would like to find an object. There is only one object with the variable x=10.
Is it possible? I hope you get what I try to explain... :)
if (any object of the class X .getValue() == 10)
...
Class X
public int getValue(){
return x;
}
List<X> xList = new ArrayList<>();
public static X findXWithValue(List<X> xList, int value) {
X xWithValue = null;
for(int i = 0 ; i < xList.size()-1 ; i++) {
if (value == xList[i].getValue()) {
xWithValue = xList[i];
break;
}
}
return xWithValue;
}
Br,
Rakesh
Something like:
public class ObjectFinder {
public static boolean checkObject(Object o, String methodName, int value) {
return Stream.of(o.getClass().getDeclaredMethods())
.filter(method -> method.getName().equals(methodName))
.filter(m -> checkType(m, int.class))
.map(m -> {
try {
return (int) m.invoke(o);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
return 0;
}
}).anyMatch(v -> value == v);
}
private static boolean checkType(Method method, Class type) {
return method.getReturnType() == type;
}
}
and you can test it in:
public static void main(String[] args) {
System.out.println(checkObject(new X(), "valueOf", 2));
}
Related
I wondering why does this code run this way.
In this example, the print output is 4. I was thinking that if the method2 were to return a new object should it not be 3 instead?
Hopefully someone can tell me what is happening. Thanks in advance!
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.method1();
}
private void method1() {
try {
TempItem item = new TempItem(5);
method2(item);
System.out.println(item.getValue());
} catch (Exception e) {
System.out.println("Error");
}
}
private TempItem method2(TempItem item) {
item.setValue(4);
return new TempItem(3);
}
class TempItem {
int value = 2;
public TempItem(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
For homework I have to implement a Words Counter using a Dictionary.I have an inner class named Couple
protected class Couple
{ public Coppia(String key, Integer value)
{ setKey(key);
setValue(value);
}
public String toString()
{ return String.format("%-15s", key) + " | " + value; }
public String getKey()
{ return key; }
public Integer getValue()
{ return value; }
public void setKey(String key)
{ this.key = key; }
public void setValue(Integer value)
{ this.value = value; }
//campi di esemplare
private String key;
private Integer value;
}
}
I created the class WordsCounter with put,find,remove methods
class WordsCounter
{ private Couple [] a;
private int inputSize;
public WordCounter()
{ a=new Couple [10];
inputSize=0;
}
public boolean isEmpty()
{return inputSize==0;}
public int size()
{return inputSize;}
public String toString()
{String s="";
for(int i=0;i<inputSize;i++)
{s=s+a[i].toString()+"\n";
}
return s;
}
public void put(Comparable key, Comparable value)
{if(inputSize==a.length) //resize
{ Coppia [] newA=new Coppia [2*inputSize];
for(int i=0;i<inputSize;i++)
{ newA[i]=a[i];
}
a=newA;
}
for(int i=0;i<inputSize;i++) // if the word is already in, i replace the old value with the new one
{ if(a[i].getKey().equals((String)key))
{ a[i].setValue((Integer)value);
return;
}
}
//otherwise i add the word in the array
a[inputSize++]=new Couple((String)key,(Integer)value);
mergeSort(a,inputSize);
}
public void remove(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0)
{ throw new MapItemNotFoundException();
}
else
{ a[pos]=a[inputSize-1];
inputSize--;
mergeSort(a,inputSize);
}
}
public int binarySearch(Couple [] a,int start,int end,String k)
{ if(start>end)
return -1;
int mid=(start+end)/2;
if(a[mid].equals(k))
{ return mid;}
else if(k.compareTo(a[mid].getKey())<0)
{ return binarySearch(a,start,mid-1,k);
}
else if( k.compareTo(a[mid].getKey())>0)
{ return binarySearch(a,mid+1,end,k);
}
else return -1;
}
public Comparable find(Comparable key)
{ int pos=binarySearch(a,0,inputSize-1,(String)key);
if(pos<0) // the word isn't inside the array ,so i throw an exception
{ throw new MapItemNotFoundException();
}
else
{ return a[pos].getValue();
}
}
public void mergeSort(Couple [] a,int input)
{ if(input<2)
return;
int mid=input/2;
Coppia [] first=new Coppia [mid];
Coppia [] second=new Coppia [input-mid];
for(int i=0;i<first.length;i++)
{ first[i]=a[i];
}
for(int i=0;i<second.length;i++)
{ second[i]=a[i+first.length];
}
mergeSort(first,mid);
mergeSort(second,input-mid);
merges(a,first,second);
}
public void merges(Couple [] a,Couple [] b,Couple [] c)
{ int i=0;
int k=0;
int j=0;
while(i<b.length&&j<c.length)
{ if(b[k].getKey().compareTo(c[j].getKey())<0)
{ a[i++]=b[k++];
}
else
{ a[i++]=c[j++];
}
}
while(i<b.length)
{ a[i++]=b[k++];
}
while(j<c.length)
{ a[i++]=c[j++];
}
}
The main class is
public class ContatoreParoleTester
{
public static void main(String[] args)
{
FileReader read=null;
try{ read=new FileReader(in.nextLine());
}
catch(IOException e)
{
}
Scanner c=new Scanner(read);
WordCounter parole=new WordCounter();
while(c.hasNextLine())
{ Scanner token=new Scanner(c.nextLine());
token.useDelimiter("[^A-Za-z0-9]+");
while(token.hasNext())
{
String tok=token.next();
tok=tok.toLowerCase();
try{
Comparable n= parole.find(tok); // i find the word ,if it isn't inside (the method throw an exception message) i catch the exception and i insert the word in the array with value=1; else i insert it in the array with the new value
parole.put(tok,(Integer)n+1);
}
catch(MapItemNotFoundException e)
{ parole.put(tok,1);}
}
}
System.out.println(parole);
}
}
When I print the counter the variable "value" doesn't seem to update, in fact i got something like this :
word1::1
word2::1
word3::1
etc.
I think that the update method doesn't work well, but I don't know why!:(
Could anyone help me please?
Thanks
Your binary search doesn't work... It only ever returns -1. I know this because it if ever did, this line in main: parole.put(tok,(Integer)n+1); would create a ClassCastException
My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.
When I try and make a catch statement using InvalidTestScore exception java won't allow me. However when I use IllegalArgumentException, java does allow me to make it.
// George Beazer
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
Runs fine
However if i run
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScore();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
I get can't find symbol. What does it take to make your own custom exception .
InvalidTestScoreException e = new InvalidTestScore();
??? shouldn't that be:
InvalidTestScoreException e = new InvalidTestScoreException();
As #Falmarri pointed out, you need to declare an InvalidTestScoreException class
Here is what a revised version might look like:
public class TestScores2 {
public class InvalidTestScoreException extends RuntimeException {
//Constructors go here
}
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScoreException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
I would like to implement a trampoline in java by returning a thunk whenever I hit a StackOverflowError. Are there any guarantees about the StackOverflowError, like, if the only thing I do after the StackOverflowError is creating objects on the heap and returning from functions, I will be fine?
If the above sounds vague, I have added some code for computing even/odd in a tail-recursive manner in continuation passing style, returning a delayed thunk whenever the stack flows over. The code works on my machine, but does Java guarantee that it will always work?
public class CPS {
public static class Thunk {
final Object r;
final Continuation c;
final boolean isDelayed;
public Object force() {
Thunk t = this;
while (t.isDelayed)
t = t.compute();
return t.r;
}
public Thunk compute() {
return this;
}
public Thunk(Object answer) {
isDelayed = false;
r = answer;
c = null;
}
public Thunk(Object intermediate, Continuation cont) {
r = intermediate;
c = cont;
isDelayed = true;
}
}
public static class Continuation {
public Thunk apply(Object result) {
return new Thunk(result);
}
}
public static Thunk even(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(true);
else return odd(n-1, c);
} catch (StackOverflowError x) {
return new Thunk(n, c) {
public Thunk compute() {
return even(((Integer)n).intValue(), c);
}
};
}
}
public static Thunk odd(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(false);
else return even(n-1, c);
} catch (StackOverflowError x) {
return new Thunk(n, c) {
public Thunk compute() {
return odd(((Integer)n).intValue(), c);
}
};
}
}
public static void main(String args[]) {
System.out.println(even(100001, new Continuation()).force());
}
}
I tried the following implementation possibilities:
A) With thunks (see code CPS below)
B) Without thunks as suggested by chris (see code CPS2 below)
C) With thunks with the stack overflow replaced by a depth check (see code CPS3 below)
In each case I checked if 100,000,000 is an even number. This check lasted
A) about 2 seconds
B) about 17 seconds
C) about 0.2 seconds
So returning from a long chain of functions is match faster than throwing an exception that unwinds that chain. Also, instead of waiting for a stack overflow, it is much faster to just record the recursion depth and unwind at depth 1000.
Code for CPS:
public class CPS {
public static class Thunk {
final Object r;
final boolean isDelayed;
public Object force() {
Thunk t = this;
while (t.isDelayed)
t = t.compute();
return t.r;
}
public Thunk compute() {
return this;
}
public Thunk(Object answer) {
isDelayed = false;
r = answer;
}
public Thunk() {
isDelayed = true;
r = null;
}
}
public static class Continuation {
public Thunk apply(Object result) {
return new Thunk(result);
}
}
public static Thunk even(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(true);
else return odd(n-1, c);
} catch (StackOverflowError x) {
return new Thunk() {
public Thunk compute() {
return even(n, c);
}
};
}
}
public static Thunk odd(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(false);
else return even(n-1, c);
} catch (StackOverflowError x) {
return new Thunk() {
public Thunk compute() {
return odd(n, c);
}
};
}
}
public static void main(String args[]) {
long time1 = System.currentTimeMillis();
Object b = even(100000000, new Continuation()).force();
long time2 = System.currentTimeMillis();
System.out.println("time = "+(time2-time1)+", result = "+b);
}
}
Code for CPS2:
public class CPS2 {
public abstract static class Unwind extends RuntimeException {
public abstract Object compute();
public Object force() {
Unwind w = this;
do {
try {
return w.compute();
} catch (Unwind unwind) {
w = unwind;
}
} while (true);
}
}
public static class Continuation {
public Object apply(Object result) {
return result;
}
}
public static Object even(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(true);
else return odd(n-1, c);
} catch (StackOverflowError x) {
throw new Unwind() {
public Object compute() {
return even(n, c);
}
};
}
}
public static Object odd(final int n, final Continuation c) {
try {
if (n == 0) return c.apply(false);
else return even(n-1, c);
} catch (StackOverflowError x) {
return new Unwind() {
public Object compute() {
return odd(n, c);
}
};
}
}
public static void main(String args[]) {
long time1 = System.currentTimeMillis();
Unwind w = new Unwind() {
public Object compute() {
return even(100000000, new Continuation());
}
};
Object b = w.force();
long time2 = System.currentTimeMillis();
System.out.println("time = "+(time2-time1)+", result = "+b);
}
}
Code for CPS3:
public class CPS3 {
public static class Thunk {
final Object r;
final boolean isDelayed;
public Object force() {
Thunk t = this;
while (t.isDelayed)
t = t.compute();
return t.r;
}
public Thunk compute() {
return this;
}
public Thunk(Object answer) {
isDelayed = false;
r = answer;
}
public Thunk() {
isDelayed = true;
r = null;
}
}
public static class Continuation {
public Thunk apply(Object result) {
return new Thunk(result);
}
}
public static Thunk even(final int n, final Continuation c, final int depth) {
if (depth >= 1000) {
return new Thunk() {
public Thunk compute() {
return even(n, c, 0);
}
};
}
if (n == 0) return c.apply(true);
else return odd(n-1, c, depth+1);
}
public static Thunk odd(final int n, final Continuation c, final int depth) {
if (depth >= 1000) {
return new Thunk() {
public Thunk compute() {
return odd(n, c, 0);
}
};
}
if (n == 0) return c.apply(false);
else return even(n-1, c, depth+1);
}
public static void main(String args[]) {
long time1 = System.currentTimeMillis();
Object b = even(100000000, new Continuation(), 0).force();
long time2 = System.currentTimeMillis();
System.out.println("time = "+(time2-time1)+", result = "+b);
}
}
That's an interesting way to jump up the stack. It seems to work, but is probably slower than the usual way to implement this technique, which is to throw an exception that is caught $BIGNUM layers up the call stack.