Collection in Java Question

Hello everyone! I am rather new to the concept of Collections in Java (I have used extensively collections in VB).
I am trying to find how collections in java work, so I used a CASE tool that automatically generates code. I am trying to model the simplest case of a maritime company that owns some ships.
However the code that is generated by this tool can not be compiled in JBuilder. I have two classes one called "Company" and another called "Ship". The code is the following one (the errors that I receive are in the code):
//Company.java
public class Company
    public final Set getShips()
        if (ships == null)
            return java.util.Collections.EMPTY_SET;
        return java.util.Collections.unmodifiableSet(ships);
// I GET AN ERROR IN THE FOLLOWING LINE SAYING: "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 31, column 32"
    public final void addShips(Ship arg)
        if (arg != null)
            if (ships == null)
                ships = new LinkedHashSet();
            if (ships.add(arg))
                arg.setCompany(this);
// I GET AN ERROR FOLLOWING LINE : "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 48, column 35"
    public final void removeShips(Ship arg)
        if (ships != null && arg != null)
            if (ships.remove(arg))
                arg.setCompany(null);
    public Company()
    public Set ships;
    protected String CName;
//Ship.java
public class Ship
    public final Company getCompany()
        return company;
    public final void setCompany(Company arg)
        if (company != arg)
            Company temp = company;
            company = null;//to avoid infinite recursions
            if (temp != null)
                temp.removeShips(this);
            if (arg != null)
                company = arg;
                arg.addShips(this);
    public Ship()
    public Company company;
    protected String SName;
    protected int NumOfCrew;
    protected String TypeOfShip;
} I have read the Java tutorial on collections, but I was wondering if there are any good code samples on Java Collections.
I am after a code sample that implements a relationship 1 to many like one Company has many ships.
Thank you very much for your responses. I am sorry for the long post!

First of all, those errors are telling you there's a CLASSPATH problem. You need to compile and run like this:
javac -classpath . *.java
java -classpath . YourMainClassNote the "dot" after "-classpath". That tells the class loader to start looking in the current directory for the .class files it needs.
Read the Sun coding standards for Java:
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
You're using a VB coding standard. Variables should start with a lower case letter (e.g., change NumOfCrew to numOfCrew).
Make that Set of ships private, not public.
You'll have to import java.util.Set and java.util.LinkedHashSet, of course.
Bad idea having two empty constructors. A constructor should leave a class ready to go, fully initialized. I'd rewrite the Company ctor like this:
    public Company()
        this("", new LinkedHashSet());
    public Company(final String companyName, Collection ships)
        this.companyName = companyName;
        this.ships = new LinkedHashSet(ships);
    }Now your collection of ships isn't null, all ready to go. - MOD

Similar Messages

  • Interesting Java Questions. Need answers Pls

    Hi All,
    I have come accross few java question, could any one please provide best answers please?
    1. Why the wait() method is there in the Object class? Not in the Threads?
    2. Why JDBC has all interfaces & not classes?
    3. Which type of collection do u prefer to make the incoming objects in sort order?
    4. Why the hasCode() method should be implemented if we are overiding the equals(0 method?
    Please provide me best answers ASAP.
    Girish.K

    do u prefer tohttp://www.catb.org/~esr/faqs/smart-questions.html#writewell
    How To Ask Questions The Smart Way
    Eric Steven Raymond
    Rick Moen
    Write in clear, grammatical, correctly-spelled language
    We've found by experience that people who are careless and sloppy writers are usually also careless and sloppy at thinking and coding (often enough to bet on, anyway). Answering questions for careless and sloppy thinkers is not rewarding; we'd rather spend our time elsewhere.
    So expressing your question clearly and well is important. If you can't be bothered to do that, we can't be bothered to pay attention. Spend the extra effort to polish your language. It doesn't have to be stiff or formal - in fact, hacker culture values informal, slangy and humorous language used with precision. But it has to be precise; there has to be some indication that you're thinking and paying attention.
    Spell, punctuate, and capitalize correctly. Don't confuse "its" with "it's", "loose" with "lose", or "discrete" with "discreet". Don't TYPE IN ALL CAPS; this is read as shouting and considered rude. (All-smalls is only slightly less annoying, as it's difficult to read. Alan Cox can get away with it, but you can't.)
    More generally, if you write like a semi-literate b o o b you will very likely be ignored. So don't use instant-messaging shortcuts. Spelling "you" as "u" makes you look like a semi-literate b o o b to save two entire keystrokes.

  • Java Question... please help

    I am running  Snow Leopard  (mac os x version 10.6.8)
    For the past couple of years I've played gin in yahoo games.  
    Yesterday when I entered the gin lobby ...the font was so tiny
    I wasn't able to read it.   I checked Java on my computer and
    it is enabled, however I just realized when I go into the gin
    lobby... there is no java icon on the dock.   Since the font size
    is fine in all other applications, I am presuming this is a Java
    issue.  
    Help if you are able.. please and thanks

    Huh? Is this a Java question? Where's the Java? I just see a little JavaScript. Do you know how to use servlets and JSPs?
    Jesper

  • What kind of Java questions can I ask?

    Here's a change:
    I want to interview some good java people. I have lots of Java questions in mind which I could ask them, however fellow JavaGuru's
    I would like some potential questions from you which I could ask someone who claims he/she is a good java programmer??
    I am asking because I want to be as fair as possible to the applicant and not ask them questions which I think are tough etc...

    Touchy subject.
    The language is not as important, as understanding programming concepts.
    So fine, when the programmer's horizont involves some abstraction levels.
    If a programmer can write an UML class diagram for a linked list.
    If a programmer knows a design pattern Singleton.
    If a programmer can write his/her own single linked list class with sorted insertion.
    Language concepts:
    - Why:
    import java.util.*;
    Map map = new HashMap();
    - Answer:
    Hiding the choice of implementation (HashMap) by using the more general
    interface Map.
    Don't expect much on an interview though. The situation might not be
    adequate to distinghuish between the good and the bad apples.
    Talking code is a good starting point, code of your making unfortunately.
    A good programmer will hesitate to show really useful code.
    A bad programmer might have stolen his/her code.
    The problem you might have, that you are in search of an expert, not
    having the expertise in-house. In that case you might get a better
    picture, talking about which IDE would be opportune, whether he/she
    has experience with the source version system CVS, what would his/her
    ideas be about coming projects.
    That would establish a common line of communication.

  • Simple basic java question

    public static void main(String[] args)
    ..anyone know the statement as above could be start at begining , so what is the (String[ ] args) mean in java ?
    in my ideas of this statement is
    publc : indicates the statemean can be used as all class , this is open for public use
    static mean the main method can used as class method
    void indicate that the statement return nothing
    main indicate any class should be run this first.
    so my question what is the function of (String [ ] args) ? // one string array call args ?

    String[] args is indeed an array of Strings called args. The reason it's there is to collect any arguments passed to your code when you start it.
    eg. if you have a class called TestClass and you called it from the command line like this:
    java TestClass exam tomorrow oh shite
    .......then the args array would hold the four Strings:
    exam
    tomorrow
    oh
    shite

  • Updateable Report : re-display collection & Update Button question

    This a sequel to a previous Updateable Report question I had.
    Varad pointed me to this doc which has been incredibly helpful .
    http://www.oracle.com/technology/products/database/application_express/
    howtos/tabular_form.html#RESTRICTIONS
    I was\am having the following issue :
    Let's zoom to the part where we create a region to display the tabular form for the previously saved collection , and drill down to the part where we create an UPDATE EMP button for that displayed collection :
    I was not able to display the collection again when I failed the validation a 2nd time. ie, clicking on the UPDATE EMP button after it displays both the errors-post validation and after displaying the collection ( of course) would return me to the previous report pre-collection creation. When I turned debug on I found out that it was not even creating the collection and was hence deleting it before displaying the subsequent page.
    So what I did differently from what the documention instructs is as follows :
    I removed the page reference on the 'branch to page' of the UPDATE EMP button. In my case, the default 'Branch to ' Page after Processing is the same page I am using for this part of the application.
    So when I remove the reference to the page number. for that button, the page is then able to re-create the collection and hence re-display the collection so I can re-fix the 2nd error ( ... and 3rd) and finally update the report .
    Just wondering if anyone else has had the same experience ?
    Thanks !

    The columns and rows have a set format for the Id, so if you know one Id you know the row and the ids of all the other columns.
    As an example, this will show the value of column 6 when you click on any column with the function call in the Element Attributes:
    Script:
    <script type="text/javascript">
    function showCol6(col){
      var col6 = document.getElementById("f06_" + col.id.substr(4,4));
      alert(col6.value);
    </script>Element Attributes:
    onclick=showCol6(this);You could also use a Named Column template, specific to this region, to include the column values directly in the function call, but I think it's best to stick with the ApEx defaults if possible.

  • How to fetch Properties of all Survey Lists from site collection using Java Script in SharePoint 2013

    Hi,
    I am trying to fetch properties of all lists of "Survey Type" from my site collection in SharePoint 2013 using script editor web part. I am able to fetch properties of one list by mentioning its name explicitly in code but not all survey
    list.
    My task is to display Survey name , description ,Time created and URLs of all survey lists using java script in script editor web part.
    And let me know , if there is any other OOB feature of SharePoint 2013 to achieve the same. 
    Here is the code  :
    <script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
    function sharePointReady() {
         GetSurveyList();
     function GetSurveyList() {
            var spListTitle = " List Name";
             var clientContext = new SP.ClientContext.get_current();
            var oWeb = clientContext.get_web();
            this.surveyList = oWeb.get_lists().getByTitle(spListTitle);
            clientContext.load(surveyList);
            clientContext.executeQueryAsync(Function.createDelegate(this, this.GetListProperties),Function.createDelegate(this, this.onFailure));
     function GetListProperties() {
            $("#SurveyList").text("");
            var surveyTable = "<table border=1>";
            surveyTable = surveyTable.concat("<tr><td>Survey Name</td>");
            surveyTable = surveyTable.concat("<td>Survey Description</td>");
            surveyTable = surveyTable.concat("<td>Time Created</td>");
            surveyTable = surveyTable.concat("<tr><td>" + surveyList.get_title() + "</td>");
            surveyTable = surveyTable.concat("<td>" + surveyList.get_description() + "</td>");
            surveyTable = surveyTable.concat("<td>" + surveyList.get_created().format("MM/dd/yyyy hh:mm tt")+ "</td>");
                 surveyTable = surveyTable.concat("</table>");
            $("#SurveyList").append(surveyTable);
        function onFailure(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    </script>
    <div id="SurveyList"></div>

    Shifa,
    Please use search result webpart or content query webpart to list all survey list.
    Please 'propose as answer' if it helped you, also 'vote helpful' if you like this reply.

  • Forte for Java question

    By using the JDBC form wizard, I generated a swing program. Along with the java code, there is a form file which looks like an xml file. My question is how to complie and run the java source code without a forte4j IDE?
    Thanks

    One thing is you need the jdbc in your classpath or specify at runtime. Search compiler in the forte help menu - to see options.
    execution : <specify at runtime>
    java -classpath:.;postgresql.org Program
    -- above for postgresql driver residing in same directory as Program.class
    compile : javac Progam.java or javac -classpath .;postgresql.org Progam.java
    Ray

  • TextSamplerDemo.java question

    I took the TextSamplerDemo from http://java.sun.com/docs/books/tutorial/uiswing/components/text.html and stripped it down to the one thing I have a question about. Given the code below, how do I implement the toolbar button to make selected text turn bold? I've been beating my head againt this one for a couple of days now and getting nowhere.
    Any help would be deeply appeciated.
    --gary
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*; //for layout managers and more
    import java.awt.event.*; //for action events
    public class TextSamplerDemo extends JPanel
    implements ActionListener {
    private String newline = "\n";
    protected static final String textFieldString = "JTextField";
    public TextSamplerDemo() {
    setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    JToolBar toolBar = buildToolbar();
    add(toolBar);
    //Create a text pane.
    JTextPane textPane = createTextPane();
    JScrollPane paneScrollPane = new JScrollPane(textPane);
    paneScrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    paneScrollPane.setPreferredSize(new Dimension(250, 155));
    paneScrollPane.setMinimumSize(new Dimension(10, 10));
    add(textPane);
    public void actionPerformed(ActionEvent e) {
    private JTextPane createTextPane() {
    String[] initString =
    { "This is an editable JTextPane, ",            //regular
    "another ", //italic
    "styled ", //bold
    "text ", //small
    "component, " + newline, //large
    "which supports embedded components..." + newline,//regular
    newline + "JTextPane is a subclass of JEditorPane that " + newline +
    "uses a StyledEditorKit and StyledDocument, and provides " + newline +
    "cover methods for interacting with those objects."
    String[] initStyles =
    { "regular", "italic", "bold", "small", "large",
    "regular", "regular"
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
    for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    private JToolBar buildToolbar() {
    JToolBar toolBar = new JToolBar();
    toolBar.setRollover( true );
    toolBar.setFloatable( false );
    JButton boldButton = new JButton("Bold");
    boldButton.setToolTipText( "Set selected text to bold" );
    boldButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    // code here to make selected text bold
    toolBar.add( boldButton );
    return toolBar;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TextSamplerDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new TextSamplerDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    try this, but im'not sure.
    StyleContext styleContext = StyleContext.getDefaultStyleContext();
    Style def = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    Style bold = styledDocument.addStyle("bold", def);
    StyleConstants.setBold(bold, true);into the listener of your component insert this:
    int start = getSelectionStart();
    int len = getSelectionEnd() - start;
    styledDocument.setCharacterAttributes(start, len, bold, true);by gino

  • Beginner Java questions

    Hello:
    I'm looking for some guidance on a few things I am confused on. Can somebody tell me or point me in the right direction on how you would write and equivalent compound statement for
    x = 2 * x;
    sum = sum + num;
    y = y / (x +5);
    lastly
    What type of input would I use for :
    import java.util.*;
    public class Strange
    static Scanner console = new Scanner (System.in);
    public static void main (String[ ] arg)
    int x;
    int y;
    String name:
    x = console.nextInt ();
    name = console.nextLine ();
    y = console.nextInt ();
    I appreciate any guidance and help provided on this. I'm struggling to wrap my head around some of these things.

    eaolson wrote:
    BigDaddyLoveHandles wrote:
    This is obviously a homework question. Please don't expect anyone here to do your homework for you.Well, if you notice, he's asking for "guidance" and for people to "point him in the right direction". He's not stating a problem and demanding a solution like so many others. If you ask me, he's asking for help with homework in exactly the right way.
    For the first question, I would suggest reviewing this section and the following ones of the Java Tutorials:
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/operators.html
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op1.html
    I don't understand what the second question is asking for.In reply #2 the OP tried to clarify the second question:
    Well, I'm tasked wtith stating "what type of input the progragms requires and in what order the input must be provided" for the program I stated. >Beyond that, I'm not sure either and that's why I'm looking for help. "Looking for help", eh?

  • EDID and LUT - a java question

    Hi all!
    I just got my Mac Mini two days ago. I need some help in accessing certain informations to a java app I'm ought to write. I tried to google 'em up, but I got stuck. Maybe someone here could help me?
    1. How can I get EDID from my display? I've seen there's something called read-edid under linux, but I don't really know how close a relative Tiger is to linux/BSD.
    2. How can I write to LUT on my Mac?
    I suppose there are some libraries, that I can use, but I can't find them
    If not, maybe someone could direct me to a C library, so I can hopefuly run it via JNI.
    Any help would be greatly appreciated.
    TIA,
    Pablo

    blue-rose wrote:
    i don't see someone who want to help me =/ ,, if u don't want to ,, it's up to you ,, but there is no need for these words which u said to me ,, it really hurts ,, thanks all anyway =( ,,Seriously though, we help those that show that they are willing and able to do some work first. All you've posted was a classic "homework dump", and these are the typical responses to homework dump questions. Lesson learned.

  • 2 quick java questions

    hi, im working on a large grpahics project with some people, and i had a couple of simple questions.
    1) is it possible to detect the colour of a spefic pixel on an image?
    Maybe some sort of method that returns the color or something? This woudl be for collision detection, since we're going to have a character walking around a building and this is pretty much the only thing i can think of for collision.
    2) Is it possible to load a large image, and then make the screen only show a small portion of it? and then when you move, it kind of resets the focus on the larger image to your new location? This would be used to help the character move around the large map.
    Thanks for all the help!

    Youre going to want to get VERY acquainted with Image and BufferedImage, lol.
    Note the getRGB method.
    As for resizing, there are many ways to do this ranging from very simple
    to a bit complicated.
    int getRGB(int x, int y)
    Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace.
    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/image/BufferedImage.html
    http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Image.html

  • 4 basic java questions..

    ok so I already learned Java last year (in grade 11), but my teacher didn't really teach anything, we learnt everything by ourselves from the API... so theres a lot of things I actually don't understand, but for now I want to ask 4 basic questions:
    1. What does static mean?
    2. Why would u "final" a constant variable? ie. If you have a variable called SIZE which is set to 5, so if u want it to be a constant, just never change its value. But what does the keyword final do to it?
    3. What's super? I see it sometimes, and my teacher showed us in the applet exampls to use super.paint(g) or somethign like that for the paint method, but I never use that because I noticed it works fine without it..
    4. Whats a question mark? I saw a game that was made in java and it had a lot of places where it had a question mark , which was part of the syntax. For example,
    int j1 = i != 0 ? i - 1 : 199;
    OR
    JUMPVEL = (fSuperSlime) ? 65 : 31;
    I really don't understand these lines...
    feel free to answer any of these questions...

    wow cool...thanks.. that question mark thing is nice
    saves a few lines..
    now, about super, so u mean u can access the parent
    class's variables?Variables, methods, constructors, if the access level is such that it's allowed.
    This will be covered in any tutorial or text though.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.
    James Gosling's The Java Programming Language. Gosling is
    the creator of Java. It doesn't get much more authoratative than this.

  • Jli.dll: why it's is not a Java question?

    jli.dll came with the downloaded program. Why lock my question?

    probably because this is not a scite forum. certainly I had no idea what is was when I read your post.
    -- and becuase this post doesn't say that the downloaded program is actually the JDK (or is it??) - if you make us guess what you could have actually told us - we are less likely to feel inclined to help you - don't assume we can read your mind.
    however I have done a few moments research and it looks like it might be vaguely java related (but not java compiler related).
    My windows install of java indeed does contain a jli.dll so if your's does not, it might be stuffed, and if the msi is corrupt, that might be why it didn't get installed.
    I would try to download a new copy and reinstall the JDK and see what what happens. If there are problems (basic JDK problems - not skite problems) then post to the [ new to java|http://forums.sun.com/forum.jspa?forumID=54] forum for assistance. for skite problems go ask skite site.

  • Urlencoder : java question...

    Hi,
    I have a question on url encoding...
    I have to open a file from the remote location and
    I have file with the name something like this...: "{0EC79CFA-9AD5-4120-A768-BD3FBFA9BF6A}_2003_0816Image0006.JPG"
    I want to open this file after encoding the file name using urlencoder.
    Please suggest me how to do this. Please give me a sample code to for this...

    You are being way too vague. I cannot tell if the file is to be opened in a browser or on a server. And you still have not explained what this has to do with JSF. It is is not a JSF-specific question, take it to the general Java forum. [But not before reading this over|http://www.catb.org/~esr/faqs/smart-questions.html] .

Maybe you are looking for

  • Year to Date and Monthly totals

    I know that this is rather simplistic, but I'm new to Discoverer and need to set up a bunch of sales reports with MTD and YTD columns. I'm going to be using the same SQL query for many of my reports but customizing the reports to show sales by state,

  • ABAP code error.

    Dear Experts, In the below abap code i am facing the problem of goods returns and other issues. becoz of that my code add the qty & value of that invoices. please give me suggestion. Please go through the bold area. SELECT-OPTIONS : s_spart FOR vbrk-

  • URGENT. PLEASE HELP. ASAP!!!

    I have a 4th gen. Ipod touch, and a few months ago, it stopped showing in Itunes, although it showed in My Computer (by the way I use Windows XP). I have the latest Itunes + QuickTime version and my Ipod is not jailbroken. It is running on iOS 4.2.1.

  • Dynamic xsql generation

    hi all Is there anyway to dynamically generate a ".xsql" page which can be processed by the xsql Servlet rather than having a static ".xsql" file on the document root of the server. all help would be appreciated. thanks in advance gp null

  • Annoying Weather Widget Problem

    This is weird - my girlfriend's MacMini, running 10.4.2 has a weather widget that "holds" the info for the 6 days that are displayed. When it's empty she just goes on line, launches the widget and voila - 6 day forecast that stays there for 6 days. I