Java class with pairs of static array values - java

I am creating a certain class using
MyClass class1 = new MyClass(ClassA.StaticSet1, ClassA.StaticCoef1);
MyClass class2 = new MyClass(ClassB.StaticSet1, ClassB.StaticCoef1);
so I wanted to gather all these static values in one class and call them using something like
MyClass class1 = new MyClass(TopClass.Obj1);
MyClass class2 = new MyClass(TopClass.Obj2);
where Obj1 and Obj2 are static entities containing the abovementioned pairs of values.
the closest thing I could do was creating static classes inside TopClass and extending one base class
so I got this ugly implementation
Public class TopClass{
public static class Base{
public String set[];
public double coef[];
public Base(s, c){
set = s;
coef = c;
}
}
public static class Obj1 extends Base{
public static String set[] = {"a","b","C"};
public static double coef[]= {1,2,3};
public Obj1(){
super(set, coef);
}
}
public static class Obj2 extends Base{
public static String set[] = {"x","y","z"};
public static double coef[]= {11,12,13};
public Obj2(){
super(set, coef);
}
}
}
then I call them with
Myclass class1 = new MyClass((TopClass.Base)(new TopClass.Obj1());
Myclass class2 = new MyClass((TopClass.Base)(new TopClass.Obj2());
but this wasn't what I exactly wanted because the class became cumbersome especially that I will be creating many of these entries.
any insight would be much appreciated :)
thanks,
Hani

This would be a great place to use a Factory pattern. Maybe something like:
public class SetCoefProvider {
private String[] set;
private double[] coef;
public SetCoefProvider(String[] set, double[] coef) {
this.set = set;
this.coef = coef;
}
public String[] getSet() {
return set;
}
public double[] getCoef() {
return coef;
}
}
public class SetCoefProviderFactory {
public static SetCoefProvider createObj1Provider() {
return new SetCoefProvider(new String[] {"a", "b", "c"}, new double[] {1,2,3});
}
public static SetCoefProvider createObj2Provider() {
return new SetCoefProvider(new String[] {"x", "y", "z"}, new double[] {11,12,13});
}
}
and then if you really want them to be singletons, you can always do something like:
public class SingletonSetCoefProviders {
private static SetCoefProvider obj1Provider, obj2Provider;
static {
obj1Provider = SetCoefProviderFactory.createObj1Provider();
obj2Provider = SetCoefProviderFactory.createObj2Provider();
}
public static SetCoefProvider getObj1Provider() {
return obj1Provider;
}
public static SetCoefProvider getObj2Provider() {
return obj2Provider;
}
}

I will be creating many of these entries. any insight would be much appreciated :)
The idea is that with statics, you don't want to make many of them, that's the whole point of a static thing. Rethink and/or re-ask with more context about your goals, what you're intending to accomplish isn't clear.

i would encapsulates the Object1 and object2, the why is to make sure that they are available to use and access, at least they are not null. see below:
public static TopClass(){
private static Object obj01 = null;
private static Object obj02 = null;
public Object getObj01(){
if(obj01 == null){
obj01 = new Object();
}
return (obj01);
}
public Object getObj02(){
if(obj02 == null){
obj02 = new Object();
}
return (obj02);
}
}
or in your case the objects are in array tipe [],.

i don't get the static part. why not do something like:
import java.util.*;
interface Foo {
String[] set();
double[] coef();
}
class FooImpl1 implements Foo {
#Override public String[] set() {
return set;
}
#Override public double[] coef() {
return coef;
}
String set[]={"a","b","C"};
double coef[]={1,2,3};
}
class FooImpl2 implements Foo {
#Override public String[] set() {
return set;
}
#Override public double[] coef() {
return coef;
}
String set[] = {"x","y","z"};
double coef[]= {11,12,13};
}
interface Bar {
Foo foo1=new FooImpl1();
Foo foo2=new FooImpl2();
}
public class So9577640 {
public static void main(String[] args) {
Foo foo1=new FooImpl1();
System.out.println(Arrays.asList(foo1.set()));
Foo foo2=new FooImpl2();
System.out.println(Arrays.asList(foo2.set()));
System.out.println(Arrays.asList(Bar.foo1.set()));
System.out.println(Arrays.asList(Bar.foo2.set()));
}
}

Related

Java: Objects that always have the same content?

I want to desrcibe my question with an example:
Base.java:
public class Base {
//NO annotations
public AnyClass anyObj;
public Base(){}
}
DerivedOne .java:
public class DerivedOne extends Base{
#SomeAnnotionsOne
public AnyClass anyObjWithAnnotations;
public DerivedOne (AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
DerivedTwo.java:
public class DerivedTwo extends Base {
//These annoations differ from #SomeAnnotionsOne
#SomeAnnotionsTwo
public AnyClass anyObjWithAnnotations;
public Derived_Two(AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
So i just want anyObjWithAnnotations always be equal to anyObj.
Example main:
public static void main(String[] args){
DerivedOne derivedObj = new DerivedOne(new AnyClass());
derivedObj.anyObj = null;
if(derivedObj.anyObjWithAnnotations == null){
System.out.println("anyObjWithAnnotations : is null");
}
}
Nothing is printed. anyObj is null, anyObjWithAnnotations isn't.
My Question:
Is it possible that anyObj is always the same as anyObjWithAnnotations??
So even if i set one of them to null or create a new instance of AnyClass with new the other variable should have the same new content.
EDIT:
Changed whole example to clarify the problem.
You can use below code, where i am creating object 1 time only and then assign its reference into second object. In this way if a value is changed in one object, in example t1, it will be reflected into t2 as well.
class Test {
private int val;
public Test(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class TestSame {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2=t1;
System.out.println(t1.getVal());
System.out.println(t2.getVal());
t1.setVal(20);
System.out.println(t1.getVal());
System.out.println(t2.getVal());
}
}
O/P :-
10
10
20
20
You can also check that both t1 and t2 has same hashcode value
System.out.println("t1 hashcode "+ t1.hashCode());
System.out.println("t2 hashcode "+ t2.hashCode());
Looks like you need a singleton.
public class Singleton {
private int val = 0;
public void setVal(int val) {
this.val = val;
}
public static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return INSTANCE;
}
}
Usage example:
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s1.setVal(42);
If singleton is too much for your case you can use approach:
Object obj1 = new Object();
final Object obj2 = obj1;
since obj2 is final reference - you will not be able to change(reassign) it. So, obj2 and obj1 will refer the same Object instance. But it is possible to reassign obj1 reference. If you set final both obj1 and obj2 - you'll get exactly what you want.
final Object obj1 = new Object();
final Object obj2 = obj1;

Is it possible to update a reference in a method?

I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}

how do I copy an object containing collections as fields

consider the below code:
public class Bid {
private double pe;
private List<ResChar> resourceList;
protected Map<Integer,Integer>scheduleOfSeller ;
public Map<Integer, Integer> getScheduleOfSeller() {
return scheduleOfSeller;
}
public void setScheduleOfSeller(Map<Integer, Integer> scheduleOfSeller) {
this.scheduleOfSeller = scheduleOfSeller;
}
private int bidId;
public int getBidId() {
return bidId;
}
public void setBidId(int bidId) {
this.bidId = bidId;
}
public double getPe() {
return pe;
}
public void setPe(double pe) {
this.pe = pe;
}
public List<ResChar> getResourceList() {
return resourceList;
}
public void setResourceList(List<ResChar> resourceList) {
this.resourceList = resourceList;
}
public Bid(int bidId,double pe, List<ResChar> resourceList){
setBidId(bidId);
setPe(pe);
setResourceList(resourceList);
this.scheduleOfSeller = new HashMap<Integer,Integer>();
}
}
I want to make a copy constructor of the bid like this :
public class BidCopy{
public Bid bid;
public BidCopy(Bid bidBuyer){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bidBuyer.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.bid = bidBuyer;
this.bid.setResourceList(resList);
}
}
The only solution that I know to make such copy is to proceed like follows :
public class BidCopy{
public Bid copy;
public BidCopy(Bid bid){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bid.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.copy = new Bid(bid.getBidId(), bid.getPe(), resList);
}
}
So I want to know if there is any other solution to make a copy of "Bid" Object more effectively ?
I would suggest making a copy constructor for your Bid object (and not a specific class for copying), a Bid is made out of its fields and not methods, like so:
public class Bid {
int ID;
String description;
Object bidStuff;
// ...as before
public Bid(Bid bid) {
this.ID = bid.ID;
this.description = bid.description;
this.bidStuff = bid.bidStuff;
}
public static void main(String[] args) {
List<Bid> original = new ArrayList<>();
// ..populate it
List<Bid> copy = new ArrayList<>(original.size());
for (Bid b : original) {
copy.add(new Bid(b));
}
}
}
You can even make the copy constructor protected or package-protected if you don't want anyone else to mess around with making multiple copies of bids.
There is not. Even though some collections have "copy constructors", these constructors will copy the elements' references, they will not create new elements for you.
You can however "optimize" the list creation itself by submitting the size of the initial list to the constructor:
List<X> newList = new LinkedList<X>(oldList.size());

How can I get data of different types from an anonymous class

I have an object that delegates some work to another object which is implementing an interface. Then, I am creating anonymous classes implementing this interface and I would like to get information from these.
Is it okay to use a final array with a size of one as a pointer to a primitve to share data with the anonymous class?
Here is a working example of what I mean :
public class ExampleClass
{
public static final int INVALID_VALUE = -1;
public static void main(final String[] args)
{
final int[] buffer = { INVALID_VALUE }; // buffer is created
final InterfaceA iaObject = new InterfaceA()
{
#Override
public void doStuff(final String paramA)
{
buffer[0] = paramA.length(); // buffer is filled in anonymous class
}
};
final ClassA objA = new ClassA(iaObject);
objA.doStuff("hello, world");
if (buffer[0] == INVALID_VALUE) // buffer is used
{
System.err.println("Invalid length !");
}
else
{
System.err.println("The length is : " + Integer.toString(buffer[0]));
}
}
public static class ClassA
{
private final InterfaceA iaObject;
public ClassA(final InterfaceA iaObject)
{
this.iaObject = iaObject;
}
public void doStuff(final String paramA)
{
this.iaObject.doStuff(paramA);
}
}
public static interface InterfaceA
{
void doStuff(String paramA);
}
}
Thanks
Suggestion: why not using a generic for an out parameter?
interface InterfaceA {
public <T> void doStuff( String paramA, Holder<T> holder );
}
class Holder<T> {
public T t;
}
Full example:
public class ExampleClass
{
public static final int INVALID_VALUE = -1;
public static void main(final String[] args)
{
final InterfaceA< Integer > iaObject = new InterfaceA< Integer >() {
#Override
public Integer doStuff( String paramA, Holder<Integer> holder ) {
return holder.value = paramA.length();
}
};
final ClassA<Integer> objA = new ClassA<>( iaObject );
int result = objA.doStuff("hello, world", new Holder<>( INVALID_VALUE ));
if( result == INVALID_VALUE ) {
System.err.println("Invalid length !");
}
else {
System.err.println("The length is : " + Integer.toString( result ));
}
}
public static class ClassA<T> {
private final InterfaceA<T> iaObject;
public ClassA( final InterfaceA<T> iaObject_ ) {
this.iaObject = iaObject_;
}
public T doStuff( final String paramA, Holder<T> holder ) {
return this.iaObject.doStuff( paramA, holder );
}
}
public static interface InterfaceA<T> {
public T doStuff( String paramA, Holder<T> resultHolder );
}
public static class Holder<T> {
public T value;
public Holder( T value_ ) {
value = value_;
}
}
}
If I understand the gist of your question, you're wondering if it is good design principle to use a final array as a wrapper to share memory between an anonymous inner class and its enclosing class.
In my experience, this is a pretty poor way of sharing data between two objects. It is probably wiser to declare your interface differently. Either return an object or use a generic to specify what type you expect back from your anonymous class.
I think one of the largest problems with your approach is the lack of encapsulation - your InterfaceA implementation uses some "global" data holder (the array), and there is no way to prevent that this array can be used elsewhere, which in turn could lead to all kinds of problems (race conditions or whatever).
A cleaner way would be the definition of some separate class (or interface) with a getInt()-method or something similar.

Delegating method calls using variable number of arguments

This question came up in the course of my work programming; it's become irrelevant to the current task, but I'm still curious if anyone has an answer.
In Java 1.5 and up you can have a method signature using a variable number of arguments, with an ellipsis syntax:
public void run(Foo... foos) {
if (foos != null) {
for (Foo foo: foos) { //converted from array notation using autoboxing
foo.bar();
}
}
}
Suppose I want to do some operation on each foo in the foos list, and then delegate this call to some field on my object, preserving the same API. How can I do it? What I want is this:
public void run(Foo... foos) {
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public void run(MyFoo... myFoos) {
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) { //converted from array notation using autoboxing
myFoo.bar();
}
}
}
This doesn't compile. How can I accomplish this (passing a variable number of MyFoo's to the run(MyFoo...) method)?
Is this what you want?
public class VarArgsTest {
public static class Foo {}
public static class MyFoo extends Foo {
public MyFoo(Foo foo) {}
}
public static void func(Foo... foos) {
MyFoo [] myfoos = new MyFoo[foos.length];
int i=0;
for (Foo foo : foos) {
myfoos[i++] = new MyFoo(foo);
}
func(myfoos);
}
public static void func(MyFoo... myfoos) {
for (MyFoo m : myfoos) {
System.out.println(m);
}
}
public static void main(String [] args) throws Exception {
func(new Foo(), new Foo(), new Foo());
}
}
I tried it and did NOT get a compile error. What is the actual error you are seeing? Here is the code I used. Perhaps i did something different:
public class MultipleArgs {
public static void main(String [] args){
run(new Foo("foo1"), new Foo("foo2"), new Foo("foo3"));
}
public static void run(Foo... foos){
MyFoo[] myFoos = null;
if (foos != null) {
myFoos = new MyFoo[foos.length];
for (int i = 0; i < foos.length; i++) {
myFoos[i] = wrap(foos[i]);
}
}
run(myFoos);
}
public static void run(MyFoo... myFoos){
if (myFoos!= null) {
for (MyFoo myFoo: myFoos) {
myFoo.bar();
}
}
}
private static class Foo {
public final String s;
public Foo(String s){
this.s = s;
}
#Override
public String toString(){
return s;
}
}
private static class MyFoo{
private final String s;
public MyFoo(String s){
this.s = s;
}
public void bar(){
System.out.println(s);
}
#Override
public String toString(){
return s;
}
}
private static MyFoo wrap(Foo foo){
return new MyFoo(foo.s);
}
}
This doesn't answer your question; it's incidental, but you don't need the null test. Here's proof:
public class VarargsTest extends TestCase {
public void testVarargs() throws Exception {
assertEquals(0, fn());
}
private int fn(String...strings) {
return strings.length;
}
}
If the method is called without any arguments, the varargs list is an empty array, not null.
I think the actual solution to your question would be to rename the second function.
use java reflections.

Categories