Java object in method argument

How to pass in any Object type into a method? Java

Note: the NPE error has been fixed I need a way to identify an Object when it is passed into a method. It can be by name or anything else unique to the Object, but not by type or value, since there may be other Objects with the same type or value in the HashMap. In TOES.java:

import java.util.HashMap; public class TOES< private HashMap> TOES = new HashMap>(); public void add(Object foot, String tag, Object data) < HashMapTOE = TOES.get(foot); if(TOE == null)< TOE = new HashMap; > TOE.put(tag, data); TOES.put(foot, TOE); > public Object val(Object foot, String tag) < return TOES.get(foot).get(tag); >> 

When TOESTest1 is run, it shows an error for the last println and the return in the val method. The output should be:

(Ignore the weird names, TOES is an acronym) I am new to java, but not new to programming (I know C++), so.

That’s not your code — it can’t be, because you’re using class as a variable name. Show us your actual code and we’re more likely to be able to help.

You’re not going to get a NullPointerException if you’re using a type instead of another, but because your reference (your variable) is null. If the type wasn’t compatible (i.e. ArrayList vs HashMap ), you’d get a ClassCastException instead.

3 Answers 3

You can do that by using a Map and the Optional class implemented since Java 8.

The Map is gonna contain the String identifier and the Object you want to pass.

Map> mapToSendToMethod = new HashMap>(); mapToSendToMethod.put("This is a string", Optional.of("This is a test")); List ListToSend = new ArrayList<>(); mapToSendToMethod.put("This is a List", Optional.of(ListToSend)); mapToSendToMethod.put("This is a number", Optional.of(123));` someMethod(mapToSendToMethod);` 

to get the object inside Optional you can use the method Optional.get() which it will return the object if there’s any, otherwise null .

is a shorthand for , it’s also known as an unbounded wildcard. So you can specify any type of object in your generic.

int doesn’t inherit from Object in Java. You can cast your int s to Integer s, and then you’ll be able to pass them to a function that takes Objects.

From Java 5 onward, autoboxing will create an Integer where an int is passed, and vice versa, without needing an explicit cast.

Because you are saying you are new to Java and know C++, the biggest difference in Java with C++ is in Java everything is pointer, in exception the native. So when you declare

a still haven’t initialized and not pointing to anything, which differ from C++ where it’s initialized with Empty Constructor.

update

Of course you are getting NPE, you haven’t initialized the TOE. Fix add method like this

public void add(Object foot, String tag, Object data) < HashMapTOE = TOES.get(foot); if (TOE == null) < TOE = new HashMap(); > TOE.put(tag, data); TOES.put(foot, TOE); > 

end of update

You are looking for equality by reference. Instead of using HashMap, uses IdentityHashMap

. in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

Instead of comparing equality with .equals method, it’s comparing with the reference (pointer address) of the object.

Читайте также:  Пример DIV, перекрывающего весь экран

There is also a warning thought.

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

Источник

Passing Information to a Method or a Constructor

The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor. For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:

public double computePayment( double loanAmt, double rate, double futureValue, int numPeriods) < double interest = rate / 100.0; double partial1 = Math.pow((1 + interest), - numPeriods); double denominator = (1 - partial1) / interest; double answer = (-loanAmt / denominator) - ((futureValue * partial1) / denominator); return answer; >

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer. The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.

Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration’s parameters in type and order.

Parameter Types

You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.

Here’s an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):

public Polygon polygonFrom(Point[] corners) < // method body goes here >

Note: If you want to pass a method into a method, then use a lambda expression or a method reference.

Arbitrary Number of Arguments

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don’t know how many of a particular type of argument will be passed to the method. It’s a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, . ), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point. corners) < int numberOfSides = corners.length; double squareOfSide1, lengthOfSide1; squareOfSide1 = (corners[1].x - corners[0].x) * (corners[1].x - corners[0].x) + (corners[1].y - corners[0].y) * (corners[1].y - corners[0].y); lengthOfSide1 = Math.sqrt(squareOfSide1); // more method body code follows that creates and returns a // polygon connecting the Points >

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.

Читайте также:  Importing numpy in python

You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object. args)

allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);
System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email);

or with yet a different number of arguments.

Parameter Names

When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.

The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.

A parameter can have the same name as one of the class’s fields. If this is the case, the parameter is said to shadow the field. Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field. For example, consider the following Circle class and its setOrigin method:

The Circle class has three fields: x , y , and radius . The setOrigin method has two parameters, each of which has the same name as one of the fields. Each method parameter shadows the field that shares its name. So using the simple names x or y within the body of the method refers to the parameter, not to the field. To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled «Using the this Keyword.»

Passing Primitive Data Type Arguments

Primitive arguments, such as an int or a double , are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example:

public class PassPrimitiveByValue < public static void main(String[] args) < int x = 3; // invoke passMethod() with // x as argument passMethod(x); // print x to see if its // value has changed System.out.println("After invoking passMethod, x codeblock"> 
After invoking passMethod, x = 3

Passing Reference Data Type Arguments

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

For example, consider a method in an arbitrary class that moves Circle objects:

public void moveCircle(Circle circle, int deltaX, int deltaY) < // code to move origin of circle to x+deltaX, y+deltaY circle.setX(circle.getX() + deltaX); circle.setY(circle.getY() + deltaY); // code to assign a new reference to circle circle = new Circle(0, 0); >

Let the method be invoked with these arguments:

Inside the method, circle initially refers to myCircle . The method changes the x and y coordinates of the object that circle references (that is, myCircle ) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0 . This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.

Источник

Passing objects to methods java

I'm using three objects: StringBuilder , Integer , and testobject - that are passed to a method to change its state. As expected, the StringBuilder and testobject points to the same object and the state is change but it does not work for Integer object.

class testobject < int x = 1; >public class test < public static void main(String[] args)< StringBuilder s1 = new StringBuilder("String"); go(s1); System.out.println(s1); Integer s2 = new Integer("20"); go1(s2); System.out.println(s2); testobject s3 = new testobject(); go2(s3); System.out.println(s3.x); >static void go(StringBuilder s1) < s1.append("Builder"); >static void go1(Integer s2) < s2 = 1; >static void go2(testobject s3)

Integer objects are immutable. By trying to assign it to a new number, you are creating a new object.

Nothing is passed by reference in Java. (In the case of objects, they're reference types, passed by value.)

2 Answers 2

Look at your three methods:

static void go(StringBuilder s1) < s1.append("Builder"); >static void go1(Integer s2) < s2 = 1; >static void go2(testobject s3)

In go and go2 , you're making a modification to the object that the parameter value refers to.

In go1 , you're changing the value of the parameter variable itself. That's very different, and because Java always uses pass-by-value, that change isn't seen by the caller.

It's important to understand that objects aren't passed to the methods at all. Instead, references are. The value of s1 , s2 and s3 are all references. If you think of the variables as like pieces of paper, each piece of paper has a house address on it, which was copied from a piece of paper declared in main .

The method bodies of go and go2 are like visiting the house whose address is on the piece of paper, and painting the front door. If you then visit the houses using the original pieces of paper, you still see the new colours on the front doors.

The method body of go1 is like scribbling out the address written on the piece of paper, and writing a new one on there instead. That doesn't make any change to a house, nor does it change the original piece of paper.

Источник

Оцените статью