1

So i'm trying to access an attribute of a class object within an array.

document doc1 = new document(1,"Introduction to Java", "Ahmed Raya", "Summary of doc1","History of Java.docx");  
document doc2 = new document(2,"Object Oriented Programming", "Ahmed Raya", "Summary of doc2","Document2.pdf");
Object[] docary = {doc1, doc2};

I have an open(directory) function that takes the directory of an object (for example doc1's directory is "History of Java.docx". What i'm trying to do is access the directory attribute of an object within the docary array.
This is basically what i want to do: open(docary[k].directory);where k is an integer variable inputted by the user. How can i do this?
Thanks

2 Answers 2

2

Change the reference type of your declaring array to document. Also, consider renaming your document class to Document to better follow Java naming conventions. See the Google Java Style Guide for more formatting info.

document[] docary = {doc1, doc2};
docary[0].directory(); //etc
Sign up to request clarification or add additional context in comments.

1 Comment

Note that he could also cast docary[k] to the document type like this: open((document) docary[k].directory)if he need the array to be Object[]
0

Option 1) You have to change the type of the array from Object to document.

document[] docary = {doc1, doc2};

Option 2) Cast the object to document.

open(((document)docary[k]).directory)

3 Comments

Another question, can I add and delete from an array of this nature? It seems like I cannot add or delete elements unless I use an ArrayList. If so, how can I do the same thing as above with an ArrayList?
Array's size is fixed. So you cannot modify its size nor remove or add elements. To use ArrayList instead, you can do the next: ArrayList<document> arrLst = new ArrayList<document>(); arrLst.add(doc1); arrLst.add(doc2);
and to get an element: open(arrLst.get(k).directory);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.