Good evening, consider the following:
public class TestEnum implements Enumeration<String> {
private Enumeration<String> files;
private TestEnum(Vector<String> files) {
this.files = files.elements();
}
public Enumeration<String> getFiles() {
return files;
}
#Override
public boolean hasMoreElements() {
return files.hasMoreElements();
}
#Override
public String nextElement() {
return files.nextElement();
}
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("1");
vector.add("2");
vector.add("3");
vector.add("4");
vector.add("5");
TestEnum obj = new TestEnum(vector);
while(obj.getFiles().hasMoreElements()) {
System.out.println(obj.getFiles().nextElement());
}
}
}
I don't understand, where is nextElement() and hasMoreElements() methods default implementation when operating whit enumeration of strings?
I know that methods implementation should be created on programmers own and it have been created , but in line:
return files.nextElement();
I call the method nextElement() on "files" object that has another implementation? If method has my implementation then it should be call nextElement() indefinitely? Or I'm wrong?
Sorry, guys, I have found it:
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0;
public boolean hasMoreElements() {
return count < elementCount;
}
public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}
In Vector class
Related
I have a superclass called DecrementCarousel which has a method that returns an object called CarouselRun. CarouselRun has its own methods which I need to override in HalvingCarousel, but I don't know how. DecrementCarousel:
public class DecrementingCarousel {
static int [] arr ;
static int capacity;
int counter = 0;
boolean alreadyExecuted = false;
boolean alreadyRun = false;
public DecrementingCarousel(int capacity) {
DecrementingCarousel.capacity = capacity;
arr = new int[capacity];
}
public boolean addElement(int element){
if (alreadyExecuted) return false;
if (counter < capacity && element > 0) {
arr[counter] = element;
counter++;
return true;
}
return false;
}
public CarouselRun run(){
alreadyExecuted = true;
if (alreadyRun) return null;
alreadyRun = true;
return new CarouselRun();
}
}
Here are methods in CarouselRun:
public class CarouselRun {
int position = 0;
public int next() {
int count = 0;
while (count < arr.length && arr[position %= arr.length] <= 0) {
position++;
count++;
}
if (count == arr.length) return -1;
return arr[position++]--;
}
public boolean isFinished() {
for (int var: arr) {
if (var > 0) return false;
}
return true;
}
}
How to override these CarouselRun methods in a subclass called HalvingCarousel? According to the task HalvingCarousel can only extend DecrementCarousel
To override behaviour of CarouselRun you need a child class, overriding its' methods. Then you need to override DecrementingCarousel.run() in order to return the subclass of CarouselRun.
public class AnotherCarouselRun extends CarouselRun {
#Override
public int next() {
//override behaviour as needed
return 0;
}
#Override
public boolean isFinished() {
//override behaviour as needed
return false;
}
}
Override methods in AnotherCarouselRun to suit your needs.
Then override behaviour of DecrementingCatousel.run()
public class HalvingCarousel extends DecrementingCarousel {
public HalvingCarousel(int capacity) {
super(capacity);
}
#Override
public CarouselRun run() {
//do other stuff
return new AnotherCarouselRun();
}
}
AnotherCarouselRun is a CarouselRun, so you are abiding to the contract of run(). Another option is to use anonymous class:
public class HalvingCarousel extends DecrementingCarousel {
public HalvingCarousel(int capacity) {
super(capacity);
}
#Override
public CarouselRun run() {
//do other stuff
return new CarouselRun() {
//this is anonymous class
#Override
public int next() {
//override behaviour as needed
return 0;
}
#Override
public boolean isFinished() {
//override behaviour as needed
return false;
}
};
}
}
This is virtually the same as first option, but you are subclassing CarouselRun as anonymous class. They are mostly used when you need the class only once.
Inheritance
This can be done like any other simple inheritance.
You just need to declare the class HavingCarousel as a child of CarouselRun using the extends keyword and then use annotation #Override to declare that you want to override the methods of the parent class.
Parent class:
public class CarouselRun {
int position = 0;
public int next() {
System.out.println("Carousel run implementation of next()");
return 1;
}
public boolean isFinished() {
System.out.println("Carousel run implementation of isFinished()");
return true;
}
}
Child class:
public class HalvingCarousel extends CarouselRun{
#Override
public int next() {
System.out.println("HavingCarousel implementation of next()");
return 2;
}
#Override
public boolean isFinished() {
System.out.println("HavingCarousel implementation of isFinished()");
return true
}
}
Interfaces
Looking at your code it could also be worth exploring interfaces instead of inheritance. Interfaces are generally more flexible and a class can implement many interfaces while it can only inherit from one parent class so interfaces should be used if there are no strong reasons opposing that like for example a huge portion of shared code which as far as I can see you will not be having.
Interface for a carousel
public interface ICarousel {
public int next();
public boolean isFinished();
}
CarouselRun implements the interface:
public class CarouselRun implements ICarousel {
int position = 0;
#Override
public int next() {
System.out.println("Carousel run implementation of next()");
return 1;
}
#Override
public boolean isFinished() {
System.out.println("Carousel run implementation of isFinished()");
return true;
}
}
HalvingCarousel implements the interface:
public class HalvingCarousel implements ICarousel{
#Override
public int next() {
System.out.println("HavingCarousel implementation of next()");
return 2;
}
#Override
public boolean isFinished() {
System.out.println("HavingCarousel implementation of isFinished()");
return true;
}
}
Further Reading
From reading your code I believe that you still need to read more on basic Java concepts like interfaces, classes, inheritance, static vs instance attributes and modifiers. For example I can't see why you would declare your array arr as static but then initialize it in the constructor and then apparently you are trying to access the array arr in a totally unrelated instance of class CarouselRun. This will not work and it does not really make sense, but as these are basic concepts I cannot explain all of this here.
So, after this question where I basically exploits reflection for passing primitive references to modify the primitive itself, like:
_begin("Another Window", ::showAnotherWindow)
I was looking for something to make something similar possible also from java, where at the moment I am using plains primitive arrays:
private boolean[] showAnotherWindow = {false};
imgui.begin("Another Window", showAnotherWindow);
#hotkey suggested me the possibility to create a class implementing the KMutableProperty0 interface and that automatically gets and sets the corresponding variable
Example:
KMutableProperty0<Boolean> prop =
PropUtils.javaProp(this, t -> t.showAnotherWindow, (t, r) -> { t.showAnotherWindow = r; });
_begin("Another Window", prop);
So, I wanted to give it a try and implemented the following in java.
Getter:
#FunctionalInterface
public interface Getter<T> {
T get();
}
Setter:
#FunctionalInterface
public interface Setter<T> {
void set(T type);
}
And then the class itself (I just wrote the constructor, all the methods are those requested by the interface and automatically implemented by the IDE) :
public class JavaProp <T> implements KMutableProperty0<T> {
private imgui.Getter<T> getter;
private imgui.Setter<T> setter;
public JavaProp(imgui.Getter<T> getter, imgui.Setter<T> setter) {
this.getter = getter;
this.setter = setter;
}
#Override
public void set(T t) {
setter.set(t);
}
#NotNull
#Override
public Setter<T> getSetter() {
return null;
}
#Override
public T get() {
return getter.get();
}
#Nullable
#Override
public Object getDelegate() {
return null;
}
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
#Override
public T invoke() {
return null;
}
#Override
public boolean isLateinit() {
return false;
}
#Override
public boolean isConst() {
return false;
}
#NotNull
#Override
public String getName() {
return null;
}
#NotNull
#Override
public List<KParameter> getParameters() {
return null;
}
#NotNull
#Override
public KType getReturnType() {
return null;
}
#NotNull
#Override
public List<KTypeParameter> getTypeParameters() {
return null;
}
#Override
public T call(Object... objects) {
return null;
}
#Override
public T callBy(Map<KParameter, ?> map) {
return null;
}
#Nullable
#Override
public KVisibility getVisibility() {
return null;
}
#Override
public boolean isFinal() {
return false;
}
#Override
public boolean isOpen() {
return false;
}
#Override
public boolean isAbstract() {
return false;
}
#NotNull
#Override
public List<Annotation> getAnnotations() {
return null;
}
}
But whenever I try to run that, I get the following:
Error:(45, 12) java: reference to Getter is ambiguous
both interface kotlin.reflect.KProperty0.Getter in kotlin.reflect.KProperty0 and interface kotlin.reflect.KProperty.Getter in kotlin.reflect.KProperty match
The problematic function is this one:
#NotNull
#Override
public Getter<T> getGetter() {
return null;
}
And the relevant file is kotlin.reflect.KProperty.tk, you can find it here
Any idea how could I solve it?
Just specify which interface you mean:
public KProperty0.Getter<T> getGetter()
But I would prefer to implement the class in Kotlin and only consume it from Java.
SSCCE:
public class Test {
public Test() {
new Anonymous1() {
void validate() {
new Anonymous2() {
int calculate() {
return Math.abs(Anonymous1.this.getValue()); // compilation error - Anonymous1 is not an enclosing class
}
};
}
};
}
}
abstract class Anonymous1 {
abstract void validate();
int getValue() {
return 0;
}
}
abstract class Anonymous2 {
abstract int calculate();
}
I know that it looks complicated and unusable, but I am just wonder is it possible to point to Anonymous1 class from Anonymous2 using .this pointer, or in any else way.
You need to do it in the class.
public Test() {
new Anonymous1() {
void validate() {
final Object this1 = this;
new Anonymous2() {
int calculate() {
return Math.abs(this1.getValue());
}
}
}
}
}
or even better, extract the things you need first and use effectively final added in Java 8.
public Test() {
new Anonymous1() {
void validate() {
int value = getValue();
new Anonymous2() {
int calculate() {
return Math.abs(value);
}
}
}
}
}
if Anonymous1 and Anonymous2 were interfaces you could use lambdas in Java 8.
public Test() {
Anonymous1 a = () -> {
int v = getValue();
Anonymous2 = a2 = () -> Math.abs(v);
};
}
I am new to Java and I am trying to learn about the implementation of Iterable & Iterator.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class ClassMates implements Iterable{
private String className;
private LinkedList<String> nameList;
public ClassMates(String className){
this.className = className;
this.nameList = new LinkedList<String>();
}
public void addName(String name){
nameList.add(name);
}
public LinkedList<String> getNameList() {
return nameList;
}
#Override
public Iterator<String> iterator() {
return new IteratorClass();
}
// Inner Class
private class IteratorClass implements Iterator<String>{
private int index;
public IteratorClass(){
this.index = 0;
}
#Override
public boolean hasNext() {
return index < nameList.size();
}
#Override
public String next() {
if(hasNext()){
int i = index;
index++;
System.out.println("This is "+ i);
return nameList.get(i);
}
throw new NoSuchElementException();
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
My question is: when I finish the implementation and try to apply the for-each to the "iterable" object, the compiler said types are not match.
Here is the main() execution for apply for-each:
public class Main {
public static void main(String[] args) {
ClassMates classMates = new ClassMates("03-01");
classMates.addName("Classmate 1");
classMates.addName("Classmate 2");
classMates.addName("Classmate 3");
classMates.addName("Classmate 4");
for(String name : classMates){
//HERE! the compiler report "String" is not match the return type of "classMates"
System.out.println(name);
}
}
Anyone can point me out the problem?
Thank you!!!
As your class will iterate through strings, you should specify the template type:
public class ClassMates implements Iterable<String>
I have to handle two classes with identical methods but they don't implement the same interface, nor do they extend the same superclass. I'm not able / not allowed to change this classes and I don't construct instances of this classes I only get objects of this.
What is the best way to avoid lots of code duplication?
One of the class:
package faa;
public class SomethingA {
private String valueOne = null;
private String valueTwo = null;
public String getValueOne() { return valueOne; }
public void setValueOne(String valueOne) { this.valueOne = valueOne; }
public String getValueTwo() { return valueTwo; }
public void setValueTwo(String valueTwo) { this.valueTwo = valueTwo; }
}
And the other...
package foo;
public class SomethingB {
private String valueOne;
private String valueTwo;
public String getValueOne() { return valueOne; }
public void setValueOne(String valueOne) { this.valueOne = valueOne; }
public String getValueTwo() { return valueTwo; }
public void setValueTwo(String valueTwo) { this.valueTwo = valueTwo; }
}
(In reality these classes are larger)
My only idea is now to create a wrapper class in this was:
public class SomethingWrapper {
private SomethingA someA;
private SomethingB someB;
public SomethingWrapper(SomethingA someA) {
//null check..
this.someA = someA;
}
public SomethingWrapper(SomethingB someB) {
//null check..
this.someB = someB;
}
public String getValueOne() {
if (this.someA != null) {
return this.someA.getValueOne();
} else {
return this.someB.getValueOne();
}
}
public void setValueOne(String valueOne) {
if (this.someA != null) {
this.someA.setValueOne(valueOne);
} else {
this.someB.setValueOne(valueOne);
}
}
public String getValueTwo() {
if (this.someA != null) {
return this.someA.getValueTwo();
} else {
return this.someB.getValueTwo();
}
}
public void setValueTwo(String valueTwo) {
if (this.someA != null) {
this.someA.setValueTwo(valueTwo);
} else {
this.someB.setValueTwo(valueTwo);
}
}
}
But I'm not realy satisfied with this solution. Is there any better / more elegant way to solve this problem?
A better solution would be to create an interface to represent the unified interface to both classes, then to write two classes implementing the interface, one that wraps an A, and another that wraps a B:
public interface SomethingWrapper {
public String getValueOne();
public void setValueOne(String valueOne);
public String getValueTwo();
public void setValueTwo(String valueTwo);
};
public class SomethingAWrapper implements SomethingWrapper {
private SomethingA someA;
public SomethingWrapper(SomethingA someA) {
this.someA = someA;
}
public String getValueOne() {
return this.someA.getValueOne();
}
public void setValueOne(String valueOne) {
this.someA.setValueOne(valueOne);
}
public String getValueTwo() {
return this.someA.getValueTwo();
}
public void setValueTwo(String valueTwo) {
this.someA.setValueTwo(valueTwo);
}
};
and then another class just like it for SomethingBWrapper.
There, a duck-typed solution. This will accept any object with valueOne, valueTwo properties and is trivially extensible to further props.
public class Wrapper
{
private final Object wrapped;
private final Map<String, Method> methods = new HashMap<String, Method>();
public Wrapper(Object w) {
wrapped = w;
try {
final Class<?> c = w.getClass();
for (String propName : new String[] { "ValueOne", "ValueTwo" }) {
final String getter = "get" + propName, setter = "set" + propName;
methods.put(getter, c.getMethod(getter));
methods.put(setter, c.getMethod(setter, String.class));
}
} catch (Exception e) { throw new RuntimeException(e); }
}
public String getValueOne() {
try { return (String)methods.get("getValueOne").invoke(wrapped); }
catch (Exception e) { throw new RuntimeException(e); }
}
public void setValueOne(String v) {
try { methods.get("setValueOne").invoke(wrapped, v); }
catch (Exception e) { throw new RuntimeException(e); }
}
public String getValueTwo() {
try { return (String)methods.get("getValueTwo").invoke(wrapped); }
catch (Exception e) { throw new RuntimeException(e); }
}
public void setValueTwo(String v) {
try { methods.get("setValueTwo").invoke(wrapped, v); }
catch (Exception e) { throw new RuntimeException(e); }
}
}
You can use a dynamic proxy to create a "bridge" between an interface you define and the classes that conform but do not implement your interface.
It all starts with an interface:
interface Something {
public String getValueOne();
public void setValueOne(String valueOne);
public String getValueTwo();
public void setValueTwo(String valueTwo);
}
Now you need an InvocationHandler, that will just forward calls to the method that matches the interface method called:
class ForwardInvocationHandler implements InvocationHandler {
private final Object wrapped;
public ForwardInvocationHandler(Object wrapped) {
this.wrapped = wrapped;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Method match = wrapped.getClass().getMethod(method.getName(), method.getParameterTypes());
return match.invoke(wrapped, args);
}
}
Then you can create your proxy (put it in a factory for easier usage):
SomethingA a = new SomethingA();
a.setValueOne("Um");
Something s = (Something)Proxy.newProxyInstance(
Something.class.getClassLoader(),
new Class[] { Something.class },
new ForwardInvocationHandler(a));
System.out.println(s.getValueOne()); // prints: Um
Another option is simpler but requires you to subclass each class and implement the created interface, simply like this:
class SomethingAImpl extends SomethingA implements Something {}
class SomethingBImpl extends SomethingB implements Something {}
(Note: you also need to create any non-default constructors)
Now use the subclasses instead of the superclasses, and refer to them through the interface:
Something o = new SomethingAImpl(); // o can also refer to a SomethingBImpl
o.setValueOne("Uno");
System.out.println(o.getValueOne()); // prints: Uno
i think your original wrapper class is the most viable option...however it can be done using reflection, your real problem is that the application is a mess...and reflection is might not be the method you are looking for
i've another proposal, which might be help: create a wrapper class which has specific functions for every type of classes...it mostly copypaste, but it forces you to use the typed thing as a parameter
class X{
public int asd() {return 0;}
}
class Y{
public int asd() {return 1;}
}
class H{
public int asd(X a){
return a.asd();
}
public int asd(Y a){
return a.asd();
}
}
usage:
System.out.println("asd"+h.asd(x));
System.out.println("asd"+h.asd(y));
i would like to note that an interface can be implemented by the ancestor too, if you are creating these classes - but just can't modify it's source, then you can still overload them from outside:
public interface II{
public int asd();
}
class XI extends X implements II{
}
class YI extends Y implements II{
}
usage:
II a=new XI();
System.out.println("asd"+a.asd());
You probably can exploit a facade along with the reflection - In my opinion it streamlines the way you access the legacy and is scalable too !
class facade{
public static getSomething(Object AorB){
Class c = AorB.getClass();
Method m = c.getMethod("getValueOne");
m.invoke(AorB);
}
...
}
I wrote a class to encapsulate the logging framework API's. Unfortunately, it's too long to put in this box.
The program is part of the project at http://www.github.com/bradleyross/tutorials with the documentation at http://bradleyross.github.io/tutorials. The code for the class bradleyross.library.helpers.ExceptionHelper in the module tutorials-common is at https://github.com/BradleyRoss/tutorials/blob/master/tutorials-common/src/main/java/bradleyross/library/helpers/ExceptionHelper.java.
The idea is that I can have the additional code that I want to make the exception statements more useful and I won't have to repeat them for each logging framework. The wrapper isn't where you eliminate code duplication. The elimination of code duplication is in not having to write multiple versions of the code that calls the wrapper and the underlying classes. See https://bradleyaross.wordpress.com/2016/05/05/java-logging-frameworks/
The class bradleyross.helpers.GenericPrinter is another wrapper that enables you to write code that works with both the PrintStream, PrintWriter, and StringWriter classes and interfaces.