I'm having a lot trouble trying to pass my list and using the .get(index) method. It keeps saying "incompatible data type" but I don't know how to make an array list get strings. Can you help? Here's my method:
//a mutator method to store the password list
public void setPasswordList(String newPasswordList)
{
ArrayList<String> pL = new ArrayList<String>(); //intalize array list store it into a list
while(true)
{
pL.add(getUserPassword());
passwordList = newPasswordList;
}
Getter method:
public String getPasswordList(){
return passwordList;
}
The line pL.add(getUserPassword()); will throw an error if the signature of your getUserPassword() function does not specify String as its return type, or a type castable to String.
So, you probabaly want to transform your ArrayList pL into a string by concatenating its elements, or maybe you could even discard the array list variable since anyway you want a string to be returned.
For example:
public void setPasswordList(String newPasswordList) {
while(true) {
passwordList = passwordList + ", " + getUserPassword();
// Hope there is some code to escape from this loop :)
}
}
Related
I have a Engineer class. And I'm creating a empty arraylist which is engineer type.
I'm creating a method to check arraylist, if arraylist isn't null it has to give me index 0. But if arraylist is null. My method has to create a new Engineer object and add to empty arraylist. After that adding, I'm expecting my method to give me index 0. But it throws IndexOutOfBoundsException. I know I missed some simple things, but I couldn't figure out how to fix.
ArrayList<Engineer> newEmptyEngineerList = new ArrayList<>();
findLastEngineer(newEmptyEngineerList);
public static void findLastEngineer(ArrayList aa){
if (aa.get(0)!=null){
System.out.println(aa.get(0));
}
else {
Engineer eng = new Engineer();
aa.add(0,eng);
System.out.println(aa.get(0));
}
}
You have to make sure that the list is not empty before calling get(0) on it.
Also avoid using raw array list and prefer interface List to its implementation when using as function parameters or return type.
public static void findLastEngineer(List<Engineer> aa) {
if (aa.isEmpty()){
aa.add(new Engineer());
}
// get and print last element
System.out.println(aa.get(aa.size() - 1));
}
This seems very simple but I can't quite figure out why this isn't working.
I want to reverse the elements in my LinkedList which I have a working method for, but I can't return the value as my prof wants it to be a void method. How would I go about this?
import java.util.LinkedList;
public class ListUtil {
public static void reverse(LinkedList<String> strings) {
LinkedList<String> reverseLinkedList = new LinkedList<>();
for(int i = strings.size() - 1; i >= 0; i--) {
reverseLinkedList.add(strings.get(i));
}
strings = reverseLinkedList;
System.out.println(strings);
}
}
import java.util.LinkedList;
public class ReverseTester {
public static void main(String[] args) {
LinkedList<String> employeeNames = new LinkedList<>();
employeeNames.addLast("Dick");
employeeNames.addLast("Harry");
employeeNames.addLast("Romeo");
employeeNames.addLast("Tom");
ListUtil.reverse(employeeNames);
System.out.println(employeeNames);
System.out.println("Expected: [Tom, Romeo, Harry, Dick]");
}
}
In my ListUtil class, it does reverse the list, but doesnt return a value (as it is void) but I don't know how to go about setting employeeName in the ReverseTester class.
I know this is probably super simple but I have not been able to figure this out for the life of me, any help is greatly appreciated.
Empty and re-fill the existing list rather than replacing it.
public static void reverse(LinkedList<String> strings) {
List<String> temp = new ArrayList<>(strings); // Copy the contents of the original list. Pass the original list to constructor of our duplicate list.
strings.clear(); // Empty the original list.
for (String e : temp)
strings.addFirst(e); // Refill the original list using elements from our duplicate list.
}
Or simply
public static void reverse(LinkedList<String> strings) {
Collections.reverse(strings);
}
Non-primitive Java object are stored by reference so you don't need to return anything from ListUtil::reverse. Any changes made to the object in the function will be reflected in ReverseTester.java. This happens because, again, non-primitive Java objects are stored by reference. Basically your code does exactly what you want it to do. You make a LinkedList, populate it with items, and then reverse those items.
You will have a problem with System.out.println(employeeNames); though. Because that will just print the object's formal name and not it's contents. If you want to print the contents of a list in Java you can do:
for (String name : employeeNames) {
System.out.println(t);
}
This is my first answer so please ask any questions if I wasn't clear enough!
I'm having trouble with my assignment and I've been scratching my head at it for a long time now. This is the criteria--
Your EmployeeNames class needs to have a static method named convertName().
The method should accept an array of last names as the input parameter.
The method should return an array of formatted names(first and middle initials and last name).
For each element, it should determine the first initial and middle initial of the name and format it correctly (ex, H. T. Smith)
It should store each of these formatted names as elements in a formatted names array.
After processing all the names, the method should return the formatted names array back to the calling program.
This is my code:
public class EmployeeNames {
String[] names;
public static String convertName(String names) {
for (int i=0; i<10; i++) {
names[i] = names.substring(names[i].length - 2, names[i].length);
}
return names;
}
}
It's not even working right now, as I'm receiving the 'array required, but java.lang.String found' error. But even after that, I'm not sure what to do. Can anyone help?
After processing all the names, the method should return the formatted
names array back to the calling program.
You'll have to change the method to return String[] instead of String.
public static String[] convertName(String[] nameString) { ... }
^
|
/* Note: I have changed it to avoid any confusions */
You'll also have to make names as static,
private static String[] names;
Edit: Thanks, #Mark for pointing out that method should also accept String[] instead of a single String object.
The issue
I'm receiving the 'array required, but java.lang.String found' error.
You have a global variable called names but also a variable called names in your method parameters.
Because they have the same name, names in your method parameters is hiding the global variable names. Since your method parameter names is declared as String instead of String[] it's throwing that error.
The fix
To solve your issue, remove the global names and change the parameter names from String to String[].
After which you'll notice that you should also change:
The return type from String to String[]
names.substring to names[i].substring
names[i].length to names[i].length() since that's the length method for String.
Changed code
The code after the changes:
public class EmployeeNames {
public static String[] convertName(String[] names) {
for (int i = 0; i < 10; i++) {
names[i] = names[i].substring(names[i].length() - 2, names[i].length());
}
return names;
}
}
I want to know if there's a way to run a method of inside an element of an Arraylist
but I don't want to do it with get because it actually changes fields of the element
thanks
benny.
You don't want to do it with get as in yourList.get(5).someMethod()?
The get method will not "extract" the element it returns, it will only return a copy of the reference. Getting + removing is the implementaiton of remove.
So, unless you have overridden the get method it will not modify the list.
Update and clarification:
List<String> list = new ArrayList<String>();
list.add(myObject); // add a reference to myObject in the list
// (remember, you can't pass around objects in java)
list.get(0).someMethod(); // get a copy of that reference and call someMethod()
Just to make everything even more clear than all the comments did:
public class ReferenceTester {
public static void main(final String[] args) {
final String original = "The One and only one";
final List<String> list = new ArrayList<String>();
list.add(original);
final String copy = list.get(0);
if (original == copy) {
System.out.println("Whoops, these are actually two references to the same object.");
} else {
System.out.println("References to a different objects? A copy?");
}
}
}
Run this class and see what it prints.
I'm trying to create a class that can instantiate arrays at runtime by giving each array a "name" created by the createtempobjectname() method. I'm having trouble making this program run. I would also like to see how I could access specific objects that were created during runtime and accessing those arrays by either changing value or accessing them. This is my mess so far, which compiles but gets a runtime exception.
import java.lang.reflect.Array;
public class arrays
{
private static String temp;
public static int name = 0;
public static Object o;
public static Class c;
public static void main(String... args)
{
assignobjectname();
//getclassname();//this is supposed to get the name of the object and somehow
//allow the arrays to become updated using more code?
}
public static void getclassname()
{
String s = c.getName();
System.out.println(s);
}
public static void assignobjectname()//this creates the object by the name returned
{ //createtempobjectname()
try
{
String object = createtempobjectname();
c = Class.forName(object);
o = Array.newInstance(c, 20);
}
catch (ClassNotFoundException exception)
{
exception.printStackTrace();
}
}
public static String createtempobjectname()
{
name++;
temp = Integer.toString(name);
return temp;
}
}
Create a Map then you can add key/value pairs when the key is your name and the value is your array.
Following up from #Ash's answer, here is some illustrative code. Notice that there is no reflection involved.
Map<String, Object> myMap = new HashMap<String, Object>();
...
Object myObject = ...
myMap.put("albert", myObject); // record something with name "albert"
...
Object someObject = myMap.get("albert"); // get the object named "albert"
// get("albert") would return null if there nothing with name "albert"
EDIT I've edited the example to use the type Object, since that is more closely aligned with what you are trying to do (I think). But you could use any type instead of Object ... just replace the type throughout the example. And you can do the same with an ArrayList; for example:
List<Date> dates = new ArrayList<Date>();
dates.add(new Date());
Date firstDate = dates.get(0);
Notice that no typecasts are required.
I expect you're getting a ClassNotFoundException from this line:
c = Class.forName(object);
The value of object the first time it's called is "1", which is not a valid class name.
Class.forName requires a class name as input, such as "java.lang.Integer". Trying to "name" your array in this way doesn't make sense to me. You need to pick an appropriate Java class name.
If you want to "name" an array instance (after you've created it), you could always store the instance as the value in a Map, using the name as the key.