I'm writing a class that will build a SQL table create statement. what I'd like to do is call a method something like createTable(String tableName ColAndTypes... ct ). When I write the method I don't get any compile errors. I'm having trouble passing the values into the method when I call it though and I think it's because my syntax is wrong and I'm not sure how to fix it. I was wondering if you could look at the example I have provided and let me know what I need to do to fix it. Thanks so much for your help!
import java.util.*;
public class foo
{
public class bar{
public String sBar1, sBar2;
public bar(){
sBar1 = "null";
sBar2 = "null";
}
public bar(String sBar1, String sBar2){
this.sBar1 = sBar1;
this.sBar2 = sBar2;
}
}
String sFoo;
List<bar> bi;
public foo(){
sFoo = "null";
bi = new bar();
}
public foo(Strinf sFoo, bar bi){
this.sFoo = sFoo;
this.bi = bi;
}
public void runFooBar(String sFoo, bar... barArgs)
{
this.sFoo = sFoo;
for(bar x:barArgs){System.out.Println(bi.get(x).sBar1 + ":" + bi.get(x).sBar2);}
}
public static void main(String[] args)
{
foo fi = new foo();
fi.runFooBar("foo 1", ("1 sBar1","1 sBar2"),("2 sBar1 ","2 sBar2"))
}//end main
}//end class
I'm not entirely sure what you're trying to do, but this fixes your syntax errors.
import java.util.ArrayList;
import java.util.List;
public class Foo {
public static class Bar {
public String sBar1, sBar2;
public Bar(String sBar1, String sBar2) {
this.sBar1 = sBar1;
this.sBar2 = sBar2;
}
}
String sFoo;
List<Bar> bi;
public Foo() {
bi = new ArrayList<>();
}
public Foo(String sFoo, List<Bar> bi) {
this.sFoo = sFoo;
this.bi = bi;
}
public final void runFooBar(String sFoo, Bar... barArgs) {
this.sFoo = sFoo;
for (Bar x : barArgs) {
System.out.println(x.sBar1 + ":" + x.sBar2);
}
}
public static void main(String[] args) {
Foo fi = new Foo();
fi.runFooBar("foo 1", new Bar("1 sBar1", "1 sBar2"), new Bar("2 sBar1", "2 sBar2"));
}//end main
}//end class
Related
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;
}
}
I am creating objects that will have properties in common based on user input and then passing the objects to a common method that will take appropriate action based on the object type.
I've been able to sort of get this working using a visitor class but it is not quite what I want. I want to be able to determine the object type in the common method and then access the methods associated with that object. I am not sure if I am close and just missing something or if I just have a bad implementation... or both =).
Here is my (complete) code:
package com.theory.bang.big;
public interface Particle
{
public enum ParticleType {
QUARK,
LEPTON
}
int processParticle(Particle p);
}
package com.theory.bang.big;
import java.util.ArrayList;
public class Quark implements Particle
{
ArrayList<String> flavorList;
/**
* Constructor for objects of class Quark
*/
public Quark()
{
flavorList = new ArrayList<String>();
flavorList.add("up");
flavorList.add("down");
flavorList.add("charm");
flavorList.add("strange");
flavorList.add("top");
flavorList.add("bottom");
}
public ArrayList<String> getFlavors()
{
return flavorList;
}
#Override
public int processParticle(Particle p)
{
System.out.println("In processParticle(Quark)");
// Never called?
return 0;
}
}
package com.theory.bang.big;
import java.util.ArrayList;
public class Lepton implements Particle
{
ArrayList<String> typeList;
/**
* Constructor for objects of class Lepton
*/
public Lepton()
{
typeList = new ArrayList<String>();
typeList.add("electron");
typeList.add("electron neutrino");
typeList.add("muon");
typeList.add("muon neutrino");
typeList.add("tau");
typeList.add("tau neutrino");
}
public ArrayList<String> getTypes()
{
return typeList;
}
#Override
public int processParticle(Particle p)
{
System.out.println("In processParticle(Lepton)");
return 0;
}
}
package com.theory.bang.big;
import java.lang.reflect.*;
class ParticleVisitor
{
public void visit( Quark q )
{
System.out.println("Quark:[" + q.getFlavors() + "]");
}
public void visit( Lepton l )
{
System.out.println("Lepton:[" + l.getTypes() + "]");
}
public void visit( Object e ) throws Exception
{
Method m = getClass().getMethod
( "visit", new Class[]{e.getClass()} );
m.invoke( this, new Object[]{e} );
}
}
package com.theory.bang.big;
import java.io.File;
public class Accelerate implements Particle
{
/**
* Constructor for objects of class Accelerate
*/
public Accelerate(Particle p)
{
processParticle(p);
}
//#Override
public int processParticle(Particle p)
{
try {
ParticleVisitor pv = new ParticleVisitor();
pv.visit(p);
} catch (Exception x) {
System.out.println(x);
}
return 0;
}
}
package com.theory.bang.big;
import java.io.File;
import java.util.Scanner;
public class Physics
{
public static void main(String[] args)
{
boolean done = false;
while (!done) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
if (input.equals("Quark")) {
System.out.println("Quark");
Quark q = new Quark();
new Accelerate(q);
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
Lepton l = new Lepton();
new Accelerate(l);
} else {
done = true;
}
}
}
}
Currently I can print the Quark flavors and Lepton types via the visit methods but what I need is to be able to execute (to be implemented) getter/setters (e.g. getSpin(), setSpin(double s)) for the respective objects in Accelerate().
What am I missing? Or is there a better way to implement this?
Thank you very much for your time.
-Walter
For your concrete example, you can throw away all that stuff and use overloading by parameter types:
public class Physics {
public static void processParticle( Quark q ) {
System.out.println("Quark:[" + q.getFlavors() + "]");
}
public static void processParticle( Lepton l ) {
System.out.println("Lepton:[" + l.getTypes() + "]");
}
public static void main(String[] args) {
boolean done = false;
while (!done) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
if (input.equals("Quark")) {
System.out.println("Quark");
Quark q = new Quark();
processParticle(q);
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
Lepton l = new Lepton();
processParticle(q);
} else {
done = true;
}
}
If you want to call processParticle() where compiler does not know the exact type of the particle, use double dispatch pattern:
// add method processParticle
public interface Particle{
...
void processParticle();
}
class Quark implements Particle {
void processParticle() {
Physics.processParticle(this);
}
}
class Lepton extends Particle {
void processParticle() {
Physics.processParticle(this);
}
}
public class Physics {
public static void main(String[] args) {
for (;;) {
System.out.print("Enter the particle [Quark or Lepton]: ");
Scanner in = new Scanner(System.in);
String input = in.next();
Particle p;
if (input.equals("Quark")) {
System.out.println("Quark");
p = new Quark();
} else if (input.equals("Lepton")) {
System.out.println("Lepton");
p = new Lepton();
} else {
break;
}
p.processParticle();
}
}
}
Then you can evolve to true visitor pattern, but reflection can and should be avoided here.
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()));
}
}
I have been trying to verify if the ThreadLocal members are indeed different in different threads.
This is my TestClass whose object I am sharing among multiple threads.
public class TestClass {
private static Set<Integer> setI;
private static ThreadLocal<Set<String>> setS;
public TestClass() {
Set<String> temp = new HashSet<String>();
for (int i=0; i<=4; i++) {
setI.add(i);
temp.add(Integer.toString(i));
}
setS.set(temp);
}
static {
setI = new HashSet<Integer>();
setS = new ThreadLocal<Set<String>>() {
protected Set<String> initialValue() {
return new HashSet<String>();
}
};
}
public static void addToIntegerSet(int i) {
synchronized(setI) {
setI.add(i);
}
}
public static void addToStringSet(String str) {
Set<String> sets = setS.get();
sets.add(str);
setS.set(sets);
}
}
the following is the class I use to test this out :-
package personal;
import java.util.*;
import personal.TestClass;
import java.lang.reflect.Field;
public class Test2 {
private static TestClass testObj;
private static Set<Set<String>> testStringSet;
private static Set<Set<Integer>> testIntegerSet;
static {
testObj = new TestClass();
testStringSet = new HashSet<Set<String>>();
testIntegerSet = new HashSet<Set<Integer>>();
}
private static void addToStringSet(Set<String> sets) {
synchronized(testStringSet) {
testStringSet.add(sets);
}
}
private static void addToIntegerSet(Set<Integer> sets) {
synchronized(testIntegerSet) {
testIntegerSet.add(sets);
}
}
private static int getTestIntegerSetSize() {
synchronized(testIntegerSet) {
return testIntegerSet.size();
}
}
private static int getTestStringSetSize() {
synchronized(testStringSet) {
return testStringSet.size();
}
}
private static class MyRunnable implements Runnable {
private TestClass tc;
private String name;
public MyRunnable(TestClass tc, int i) {
this.name = "Thread:- " + Integer.toString(i);
this.tc = tc;
}
#Override
public void run() {
try {
Field f1 = tc.getClass().getDeclaredField("setS");
Field f2 = tc.getClass().getDeclaredField("setI");
f1.setAccessible(true);
f2.setAccessible(true);
Set<String> v1 = (Set<String>)(((ThreadLocal<Set<String>>)(f1.get(tc))).get());
Set<Integer> v2 = (Set<Integer>) f2.get(tc);
addToIntegerSet(v2);
addToStringSet(v1);
} catch (Exception exp) {
System.out.println(exp);
}
}
}
public static void main(String[] args) {
for (int i=1; i<=2; i++) {
(new Thread (new MyRunnable(testObj,i))).start();
}
try {
Thread.sleep(5);
} catch (Exception exp) {
System.out.println(exp);
}
System.out.println(getTestStringSetSize());
System.out.println(getTestIntegerSetSize());
}
}
thus the 1st print statement should print out 2 and the second one should print out 1.
how ever the 1st print statement also prints out 1.
what is wrong ?
For a test class, I'd start with something much, much simpler. Just store a String or something in the ThreadLocal to start with, and avoid the reflection calls (setAccessible, etc.). Your issue is most likely in all of this extra code, and nothing due to the ThreadLocal itself.
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.