How do you know you need to define a new method? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
We want each method to do a distinct task, right? How do you draw that line?
For example, say I have a class with an int array that I need to have set to certain numbers when the class is constructed. Should I loop through the array right there or make a separate method for what is ultimately a simple task?

Make a new method whenever you have a sensible name for one. When you have a good name for a new method, it suggests that what you're doing there is a separate task and potentially reusable.
Note that this is just a rule of thumb and may not apply to all cases. Another rule is to make a new method if your current method is too long (I've heard 48 lines cited as an upper bound).

Here is a sample class that I hope points out what you are looking for:
class Sample {
private int[] myInts = null;
// we need a constructor if we are going to pass in stuff
// if we don't provide a constructor, java will create one for us
public Sample(int[] inputs) {
// I can just set this array, I don't need a separate method to
// loop through and create a new array and copy the old one.
myInts = inputs;
}
// here we are going to do something discreet, so I need a new method.
public int add() {
int returnValue = 0;
for (int i = 0; i < myInts.length; i++) {
returnValue += myInts[i];
}
return returnValue;
} // end my "add()" method
} // end my Sample class

Related

What is the difference between object and object[] in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
So i wrote a method that accepts any java object and i figured out that
public void mymethod(Object javaobject) {
}
works, but with
public void mymethod(Object[] javaobject) {
}
Eclipse trows an error
The method mymethod(Object[]) in the type myClass is not applicable for the arguments (Object)
So my question is, where is the difference between these two types ?
Simply, the difference is that Object is a single object whereas Object[] is an array (multiple or collection) of indexed objects.
For example you could have an object that contains a string like
Object obj = "Hello";
or you could have an array of strings like
Object[] objArray = new Object[2];
objArray[0] = "Hello,";
objArray[1] = " world!";
So, obj is one Object. Whereas, objArray is an array that contains multiple objects indexed starting with 0. Hopefully this helps!
An array is-a an Object, but one Object is not (necessarily) an array of Object(s). You could make your method take varargs,
public void mymethod(Object... javaobject) {
// ...
}
Then it would work like an array (that is javaobject is an array) in both cases (called with one, or more, Object(s)).

How do i convert a Set into 2D array in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So, i have a Set, where each instance has four fields.
I want to convert it to Array[i][j], where each [j] row would represent an instance.
Edit:
Ok. Sorry for my bad question construction. Im trying to make a programm, which would represent a TreeSet data in table with javax.swing.table.AbstractTableModel.
Actual problem was in AbstractTableModel's getValueAt(int r, int c) method, which needs an index for every table element. Since sets don't have an index, i decided to convert data into 2D array just for table because it makes things simple. But now i'm stuck with setValueAt(Object value,int r,int c), where i should convert edited data back to Set.
Now i'm thinking of converting this Set to List instead of array since it would be easy to transfer back.
Let be a:
public class MyClassWhithFourFields {
String field1;
int field2;
Object field3;
double field4;
}
Now you can declare a set with this template:
Set<MyClassWhithFourFields> mySet = new HashSet<MyClassWhithFourFields>();
In your Set are your objects, which has 4 fields.
If you want to declare a 2 dimension array, than what type should be?
- the most common parent can be, and in this case it is the Object.
So declare a function an implement it:
Object[][] transformSetTo2dArray(Set < MyClassWhithFourFields > mySet) {
if (mySet == null) {
return null;
}
Object[][] result = new Object[4][mySet.size()];
int j = 0;
// iterate the set:
for (MyClassWhithFourFields myObject: mySet) {
myObject[0][j] = myObject.field1;
myObject[1][j] = myObject.field2;
myObject[2][j] = myObject.field3;
myObject[3][j] = myObject.field4;
j++;
}
return result;
}

Using reference to "this" object from member variable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am asked to say what does this code do but I really cannot figure it out.
I've tried to execute it in netbeans and got the answer 6 but really cannot understand why.
public class Quattro {
int x = 5;
Quattro s = this;
Quattro f(){
s.s.s.x++;
return s;
}
void g(){System.out.println(x);}
public static void main (String[] args){
Quattro a4 = new Quattro();
a4.f().g();
}
}
Question 1: What does Quattro s = this; do? Am I declarind a pointer to my self? If so, it means that I can write
Quattro f(){
s.s.s.x++;
return s;
}
or even
Quattro f(){
s.s.s.s.s.s.s.s.x++;
return s;
}
and I'll always get the same result because I'm in a loop?
Question 2: I do not understand what a4.f().g(); does... seems so weird to me.
If you assign this reference to a member variable, you have a recursion. Yes, it doesn't matter how many s's you'll add, because they are always the same object, which is this object. It's the same as if you wrote:
this.this.this.this.this.this.x++;
Function f() returns reference to this object after doing some other operations on it. It's a common design pattern in Java, called builder. Adding ability to do a4.f().g(); to a class is called method chaining. In other words, f() is this object at the end of the call, just like s is, so you can do:
a1.f().f().f().f().f().f();
And it means you just called f() function from a1 object 6 times.

Java storing method into arraylist [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Currently I am storing method of page into array. But I want to store these method into arraylist but not sure what is wrong with it.
WizardPage[] pages={pageone(), pagetwo(), pagethree()};
versus
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
public WizardPage pageone() {
WizardPage pageone = new WizardPage("one","page 1");
Do something~
return pageone;
}
public WizardPage pagetwo() {
WizardPage pageone = new WizardPage("two","page 2");
Do something~
return pagetwo;
}
public WizardPage pagethree() {
WizardPage pageone = new WizardPage("three","page 3");
Do something~
return pagethree;
}
if you want to store the methods instead of their return values then
instead of
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
try
List<Method> pageStore = new ArrayList<Method>();
try {
pageStore.add(this.getClass().getMethod("pageone"));
pageStore.add(this.getClass().getMethod("pagetwo"));
pageStore.add(this.getClass().getMethod("pagethree"));
} catch ...
}
On an different note than the fact that you aren't actually storing the methods, but their return types, you've got this
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(pageone());
pageStore.add(pagetwo());
pageStore.add(pagethree());
Since all the methods pageX() are all instance methods, you need an instance to call them on. Assuming the class those methods appear in is called WizardBook, you would need something like
WizardBook book = new WizardBook();
List<WizardPage> pageStore = new ArrayList<WizardPage>();
pageStore.add(book.pageone());
pageStore.add(book.pagetwo());
pageStore.add(book.pagethree());
Or make the methods static.
...unless of course you are running it within an instance member context.
In Java, methods are not objects. You can't store methods in an array or ArrayList.
Fist point to say You cannot store a method, you can only store its return value.
I don't see any problem in storing the returned values into a list.
Store an array of objects. Objects have methods, so you can then access (either call or for special purposes use reflection) the methods.
What you are trying to do is unclear, but it looks as though you want 3 objects of class WizardPage, with some String fields, and which perhaps has a method like void doPageUpdateStuff(). On the other hand, maybe all the work can be done in the constructor.

How parameter.method() method works? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Well, i was thinking about that kind of methods.
They dont recive parameters, but they work with them.
An example: .replace(Char, Char) of String API, it works with a String followed by a dot.
Like:
String test = "= Text = without = equals";
String output = test.replace("=","");
How it works without receive the parameter test?
I'm just being curious, want to do a method like these.
Sorry for my bad english!
Thanks.
Let's say you build a new type of String, that only does replace stuff (why not?!):
public class MyString {
private final String s;
public MyString(String s) {
this.s = s;
}
public String replace(String search, String replace) {
return s.replace(search, replace);
}
}
Now you can call it like this:
MyString myString = new MyString("= Text = without = equals");
String output = myString.replace("=", "");
Et voila, you have done the same "trick"! And you can see how it works: your MyString object keeps some data internally (the s variable) and can access that data from its methods.
These are instance methods, which means that they require an instantiated class object to operate. So, the string class knows the value of test in your example, because it has access to the instantiated data.
To create these types of methods, simply define them within your class and do not mark them as static.
String is an object. The class definition is part of the Java standard library. That definition includes the replace method.
Since String is a final class you can not subclass it to add additional methods. So you can not do what you are trying to do.

Categories

Resources