Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
You could try Observer/Observable, but it really kind of sucks.

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
The *Listener pattern is basically a hack around Java's lack of delegates.

Essentially a delegate represents "a function with a particular signature", allowing you to pass functions around in a type-safe fashion.

In Java you can achieve sort of the same thing by declaring a one-method interface, and passing around "functors" that implement that interface. It's an ugly and verbose hack, but it does achieve the same result.

Hidden Under a Hat
May 21, 2003

MEAT TREAT posted:

On Linux systems, directories starting with a dot are hidden, maybe OS X is the same?

carry on then posted:

In Finder just hit CMD+Shift+G and type in ~/.netbeans, should take you right to it.

Thank you! That cleared it right up.

If I'm not actually using the GUI builder "drag-and-drop" aspect of Netbeans anymore, is there a better utility in which to write code?

Thom Yorke raps
Nov 2, 2004


Hidden Under a Hat posted:

Thank you! That cleared it right up.

If I'm not actually using the GUI builder "drag-and-drop" aspect of Netbeans anymore, is there a better utility in which to write code?

IntelliJ community edition

Doctor w-rw-rw-
Jun 24, 2008

Hanpan posted:

Does Java have any kind of event handling / dispatching ala Actionscript 3? I know it doesn't have delegates so the C# system I was hoping to port over won't work. The only thing I can find on Google is the ActionListener interface, but that seems to be specifically for Swing?

For reference, what I am trying to do is listen for events on a particular object. If I was coding a game, for example, I might want to listen for events for when the player jumps, takes damage or dies so the rest of my game can react accordingly.

Never used Actionscript 3, but EventBus (javadoc) in Guava might suit your fancy.

iscis
Jan 8, 2007
im the coolest guy you know
relatively simple question, but it is giving me fits. Trying to implement an array based deque, with addFront(x), addRear(x), removeFront(), removeRear(), size(), and isEmpty() methods. This is done with an array whose size is passed as an argument, and then front and rear variables that wrap around the array.
code:

public class deque {
	private String[] d;
	private int front,size,rear;

	deque(int capacity) {
		d = new String[capacity];
		front = 0;
		size = 0;
		rear=0;
	}
	
	
	public int capacity() {
		return d.length;
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public void addFront(String s) {
		if(front<0||front>d.length){
		front=front%d.length;
			
		}
			if(isEmpty()){
			d[0]=s;
			
		}
		
		else{
			
				s=d[front];
			}
			front--;
			
			
		
		size++;
	}
	

	public void addRear(String s) {
	       if (size == d.length)
	           throw new QueueOverFlowException();
	       else
	       {
	           // Add to rear
	           size ++;
	           d[rear] = s;
	           rear ++;
	           if (rear == d.length) rear = 0;           
	       }
	    }

	public String removeFront(){
        if (isEmpty())
            throw new EmptyQueueException();
        else
        {
            size --;
           // Remove from front
           String value = d[front];
			  
			  // Facilitate garbage collection  
           d[front] = null;     
			  
           // Update front
           front++;
           if (front == d.length) front = 0;
			         
           return value;        
        }
    }

	public String removeRear() {
           size --;
           // Remove from rear
           String value = d[rear];
			  
			  // Facilitate garbage collection  
           d[rear] = null;     
			  
           // Update rear
           rear--;
           
			         
           return value;        
        }
    
	public int size(){
		return size;
	}
	
	public String toString()
    {
      StringBuilder sBuilder = new StringBuilder();
      sBuilder.append("front = " + front + "; ");
      sBuilder.append("rear = " + rear + "\n");
      for (int k = 0; k < d.length; k++)
      {
          if (d[k] != null)
             sBuilder.append(k + " " + d[k]);
          else 
             sBuilder.append(k + " ?");
          if (k != d.length - 1)
			    sBuilder.append("\n");
      }
      return sBuilder.toString();        
    }
}
the addFront method will not set the front variable to the right value, which should be 9, as -1%10 (10 is the size in the test)=9, but it stays at -1, and then throws ArrayIndexOutOfBounds. No idea why

ComptimusPrime
Jan 23, 2006
Computer Transformer
Firstly, you are decrementing front after you take its modulus.

Secondly, this

code:

s=d[front];

I assume is reversed.

Airconswitch
Aug 23, 2010

Boston is truly where it all began. Join me in continuing this bold endeavor, so that future generations can say 'this is where the promise was fulfilled.'
This one's killing me. I place a "customer" into a queue with
code:
line.add(new customer(custime));
With custime holding a valid int, of course. customer is not a very complicated class:
code:
public class customer
{
	int time;
	public customer(int t)
	{
		time = t;
	}
	public int gettime()
	{
		return time;
	}
	public void tick()
	{
		time--;
	}
}
However, time is not properly assigned a value. What stupid mistake am I making here?

baquerd
Jul 2, 2007

by FactsAreUseless

Airconswitch posted:

However, time is not properly assigned a value. What stupid mistake am I making here?

Nothing looks wrong with the posted code, what do you see in the debugger when you step into the line? As an aside, Java classes are capitalized by convention.

Plank Walker
Aug 11, 2005
I'm having an issue running a piece of code from an applet. I have a method in a static class that reads a file and returns an object based on the contents of the file. However, I get a FileNotFound exception when testing the code within a JApplet.

code:
public static Board generateBoardFromFile(String filename, int row, int col) throws NumberFormatException {
    fileScanner = new Scanner(new BufferedReader(new FileReader(filename))); //exception thrown on this line
For now, the file is stored in a "/res" directory off of the main Eclipse project. The code runs fine in all non-applet testing, using "res/Filename" as the passed String. It runs under no circumstances when called from an applet, whether I'm passing the truncated file name or the absolute path as string.

Edit: Thanks baquerd

Plank Walker fucked around with this message at 00:41 on May 2, 2012

baquerd
Jul 2, 2007

by FactsAreUseless

Plank Walker posted:

I'm having an issue running a piece of code from an applet. I have a method in a static class that reads a file and returns an object based on the contents of the file. However, I get a FileNotFound exception when testing the code within a JApplet.

code:
public static Board generateBoardFromFile(String filename, int row, int col) throws NumberFormatException {
    fileScanner = new Scanner(new BufferedReader(new FileReader(filename))); //exception thrown on this line

Your applet does not run on your server, rather the client executes the applet and does not have a copy of the file. You need to access the file via a URL:
http://stackoverflow.com/questions/574675/read-file-in-an-applet

edit also this:
http://docs.oracle.com/javase/tutorial/deployment/applet/appletExecutionEnv.html

baquerd fucked around with this message at 00:11 on May 2, 2012

Doctor Malaver
May 23, 2007

Ce qui s'est passé t'a rendu plus fort
If anyone's interested in Java certification, I'm looking for reviewers for this book.

OCA Java SE7 Study Guide
Earning the Oracle Certified Associate Java Programmer I Exam is an easy task only if you prepare for it in the focused manner. Your search for a hands-on and practical guide for the exam ends here. This book will hand-hold you while imparting you with necessary knowledge through a step-by-step process and will give you confidence to pass the exam. This book is primarily for entry level Java programmers or Students studying to become a Certified Oracle Java Associate, Java programmer I.

To learn more about the whole review thing, check out this thread: http://forums.somethingawful.com/showthread.php?threadid=3463489&userid=0&perpage=40&pagenumber=1

Suran37
Feb 28, 2009
Ok, I give up. I cannot figure out how to paint a pixel I click on. I have googled for hours, and I keep finding ways to set it up, but the examples never make a call to paint(), they just set it up.
I am probably just missing something, but I have no idea what to pass when it comes to calling paint(Graphics g); I mean obviously you pass a Graphics variable, but I ave no idea what I am suppose to set it to. I suppose this is what I get for just jumping into graphics.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Suran37: You never explicitly call paint() on a Component- call repaint() and paint() will be called for you by the AWT/Swing event thread. How's this:

code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GraphicsDemo extends JPanel implements MouseListener {

	public static void main(String[] args) {
		JFrame window = new JFrame("Demo");
		GraphicsDemo app = new GraphicsDemo();
		app.setPreferredSize(new Dimension(500, 500));
		app.addMouseListener(app);
		window.add(app);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setResizable(false);
		window.pack();
		window.setVisible(true);
	}

	public void paint(Graphics g) {
		g.setColor(Color.BLACK);
		g.fillRect(lastx-5, lasty-5, 10, 10);
	}

	int lastx = 0;
	int lasty = 0;

	public void mouseClicked(MouseEvent e) {
		lastx = e.getX();
		lasty = e.getY();
		repaint();
	}

	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
}

RADmadness
Feb 17, 2011
How can I make an array take values input at the command line?

For example typing "java Calc 1 2 3 4" into the console should make an array of [1,2,3,4].

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
RADmadness: Use a Scanner attached to System.in.

I guess finals week isn't over yet, hunh?

RADmadness
Feb 17, 2011
It's not that simple. The program is tested by another program that I am not allowed to see. I cannot figure out how to let it input what it wants straight from the command line.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
It's right there in the loving main method's signature
code:
public static void main (String[] args)
If someone runs your program from the command line then args will have the array with the values. Obviously they are Strings and you need to convert them to numbers.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

edit: beaten :v: ^^^

Arguments made to the call to "java Calc" go in the args parameter of public static void main(String[] args), so if that's how you're doing it, the array is already made. That only works for starting the program; you can't do something like that if it's already running.

Suran37
Feb 28, 2009

Internet Janitor posted:

Suran37: You never explicitly call paint() on a Component- call repaint() and paint() will be called for you by the AWT/Swing event thread. How's this:

Thanks for explaining as the examples didn't have repaint() either. Anyway it still isn't working. I'm trying to copy an algorithm I saw in a different language to Java, but I may be in a little over my head. I'll take another stab at it tomorrow, and I'll post some code if I am still having troubles.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
How do I measure the pixel size of a String? Oracle's tutorial only gives a solution for the width, and says

quote:

If this solution is insufficient, other text measurement APIs in the Java 2D™ software can return rectangular bounding boxes. These boxes account for the height of the specific text to be measured and for pixelization effects.
but doesn't actually tell me what those other APIs are.

e: oh, and to ask x not y: I'm trying to find the amount of space a String actually takes. So "...." will be something like 18x2 (obv depending on font).

Malloc Voidstar fucked around with this message at 15:45 on May 4, 2012

Max Facetime
Apr 18, 2009

Aleksei Vasiliev posted:

e: oh, and to ask x not y: I'm trying to find the amount of space a String actually takes. So "...." will be something like 18x2 (obv depending on font).

public Rectangle2D getStringBounds(String str, Graphics context) in FontMetrics is probably what you want.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
If I recall correctly, getStringBounds doesn't take descenders into account, which can lead to some serious WTF moments.

Volguus
Mar 3, 2009

Internet Janitor posted:

If I recall correctly, getStringBounds doesn't take descenders into account, which can lead to some serious WTF moments.

That may be the case, but won't you have some line width anyway? Set to something like: getStringBounds("X").getHeight()*2? Or even user definable?

I'm talking out of my rear end right now, as the last time I wrote a java application that had to paint what was going to a printer was 10 years ago, but if i'm not mistaken that's how I solved the issue.

Gutrot
Dec 17, 2004

you're*
Trying to import a True TypeFace font file into a program and display it on a Frame, so that the font will appear for those who haven't got it installed on their operating system. Nothing fails or exceptions out, but it simply doesn't display text in the imported font on a Frame, and the imported font isn't listed in a call to the GraphicsEnvironment's "getAvailableFontFamilyNames()" method.

In short, the second and third lines should be looking like the fourth line:


Anyone willing to have a poke about and see what's going wrong?

The font file itself is "frogger_.ttf" from here. It's sat within "FontImportTest\build\classes\fontimporttest\resources" folder.

code:

package fontimporttest;

import java.io.File;
import java.io.IOException;
import java.awt.*;

public class FontImportTest extends Canvas {

    public FontImportTest() {

    // Invokes default constructor of "StringTest" 's superclass, "Canvas".
    super();

    // Sets the dimensions and colouration of the graphical panel to display the strings on.
    setSize( 300, 200 );
    setBackground( Color.white );

    /************************************************************************************
     * The following code governs importing the TrueType Face font from its file location
     ************************************************************************************/
    Font froggerFont;
    File fontImportFileLocation = new File( getClass().getResource( "resources" ).getFile(), "frogger_.ttf" );
    File fontImportFile = new java.io.File( fontImportFileLocation.toURI() );
    
    // Attempt to import new font embedded within try / catch in case of exception.
        try {

            froggerFont = java.awt.Font.createFont( java.awt.Font.TRUETYPE_FONT, fontImportFile );
            
            /* New font "froggerFont" defaults to a size of 1. The following line
             * converts this to a size 11 by calling the method "deriveFont" method
             * from the "Font" class that "froggerFont" is an object instance of,
             * and providing it with a Float argument value of "11.0F".
             */
            froggerFont = froggerFont.deriveFont( 11.0F );
            
            /* Registers font with the GraphicsEnvironment to check if it's actually 
             * usable, later.
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ge.registerFont( froggerFont );
            
            // Check of file location that import attempted to bring the new font in from.
            System.out.println( "Successfully imported font from " + 
                    fontImportFileLocation.toString() );

            /* Array that holds the list of all fonts known by the GraphicsEnvironment.
             * If the new font has been successfully imported, it should be among them.
             */
            String[] fontList = ge.getAvailableFontFamilyNames();
            
            System.out.println( "Available fonts:" );
            
            /* "for" loop to determine whether the newly imported font "froggerFont"
             * is listed as one of the available fonts available within the
             * GraphicsEnvironment. Prints the name of each available font in turn
             * to a new line in the console.
             */
            for( int i = 0; i < fontList.length; i++ ) {
                
                System.out.println( fontList[i] );
                
            } // end "for" loop

        } catch ( FontFormatException ex ) {

            System.out.println( ex );

        } catch ( IOException ex ) {

            System.out.println( ex );

        } // end "try/catch" statement block
        
        /**************************
         * End of font import code
         **************************/


    } // end default constructor

    public static void main(String[] args) {
        
        FontImportTest fit = new FontImportTest();
        GUIFrame frame = new GUIFrame( "Font import Test" );
        frame.add( fit );
        frame.pack();
        frame.setVisible( true );
        
    } // end main method
    
    public void paint( Graphics g ) {

       // First line should use default font 
        g.drawString( "Frogger...", 10, 10 );
        
        /* Subsequent lines should use newly imported font, the first in plain
         * text, the second in bold text.
         */
        g.setFont( new Font ( "froggerFont", Font.PLAIN, 24 ) );
        g.drawString( "Frogger?", 25, 45 );
        g.setFont( new Font ( "froggerFont", Font.BOLD, 24 ) );
        g.drawString( "Frogger?", 25, 80 );
        
        /* Final line uses the system font "Frogger", to compare with the prior
         * two lines. This will only display using the "Frogger" font if it
         * has been installed in the operating system.
         */
        g.setFont( new Font ( "Frogger", Font.BOLD, 24 ) );
        g.drawString( "Frogger?", 25, 105 );
        
    } // end method "paint"

} // end class "FontImportTest"

---------------------------------------

package fontimporttest;

/**
 * An extension of the "Frame" class imported from the Abstract Windowing Toolkit.
 * It uses a WindowAdapter to handle the WindowEvents and is centred.
 */

import java.awt.*;
import java.awt.event.*;

public class GUIFrame extends Frame {
    
    // Overridden constructor with signature "String"
    public GUIFrame ( String title ) {
        
        super( title );
        setBackground( SystemColor.control );
        
        addWindowListener( new WindowAdapter( ) {
            
            // only need to override the method needed
            public void windowClosing( WindowEvent e ) {
                dispose();
                System.exit(0);
            }
        });
    } // end overridden constructor with the signature "String"
    
    /* Centres the Frame when setVisible( true ) is called, no matter what size
     * it is when made visible.
     */
     public void setVisible( boolean visible ) {
         
         /* If the boolean argument "visible" passed in when this method is
          * invoked is true...
          */
         if ( visible ) {
             
             /* Gets the screen size by calling Toolkit.getDefaultToolkit().getScreenSize(),
              * which returns a "Dimension" object that represents the resolution
              * of the computer screen.
              * 
              * The "Toolkit" class is the absrtact subclass of all implementations
              * of the AWT, the default of which is different depending on what
              * operating system is being used.
              */
             Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
             setLocation( ( d.width - getWidth() ) /2, ( d.height - getHeight()) /2 );
             
         } // end "if" statement block
         
         super.setVisible( visible );
         
     } // end method "setVisible"
    
} // end class "GUIFrame"


Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Is registerFont actually returning true?

Max Facetime
Apr 18, 2009

The problem is likely that
code:
new Font ( "froggerFont", Font.BOLD, 24 )
claims that the family name of the font is "froggerFont" when that's not actually the case. This page here says that the font's family is actually "Frogger" and also that it's a commercial font.

Also, your download link says the size of the Frogger font is 19kb, but the size of the downloader is 154kb and it wanted administrator access to my computer, which I, of course, didn't give.

dafont.com looks like it has actually free fonts for various uses. I tested with a random font and using the correct font family name everything should work.

Devvo
Oct 29, 2010
What's a good book / set of online tutorials for learning Java if you already know how to program?

I'm a college student who knows C, C++ and Python, how to write object oriented programming for the last two, and I've taken a Data Structures class in C++. My curriculum was more mathematics based, so I've never touched Java. I'm not particularly interested in taking a Java class in the other computer science track at my university, mainly because they'll be focusing on beginner stuff, but that could be a possibility.

I'd like to learn Java (or C#, I guess) because it's the dominant language in the Real World, Android app development seems interesting, and I feel weird not knowing it when every other CS grad is fed with it.

Volguus
Mar 3, 2009

Devvo posted:

What's a good book / set of online tutorials for learning Java if you already know how to program?

I'm a college student who knows C, C++ and Python, how to write object oriented programming for the last two, and I've taken a Data Structures class in C++. My curriculum was more mathematics based, so I've never touched Java. I'm not particularly interested in taking a Java class in the other computer science track at my university, mainly because they'll be focusing on beginner stuff, but that could be a possibility.

I'd like to learn Java (or C#, I guess) because it's the dominant language in the Real World, Android app development seems interesting, and I feel weird not knowing it when every other CS grad is fed with it.

While I cannot recommend you a good Java book (there are bazillions, just pick whatever has good reviews at amazon), I would recommend reading something like Clean Code. It'll help immensely regardless of the language of choice.

Doctor w-rw-rw-
Jun 24, 2008

Devvo posted:

What's a good book / set of online tutorials for learning Java if you already know how to program?

I'm a college student who knows C, C++ and Python, how to write object oriented programming for the last two, and I've taken a Data Structures class in C++. My curriculum was more mathematics based, so I've never touched Java. I'm not particularly interested in taking a Java class in the other computer science track at my university, mainly because they'll be focusing on beginner stuff, but that could be a possibility.

I'd like to learn Java (or C#, I guess) because it's the dominant language in the Real World, Android app development seems interesting, and I feel weird not knowing it when every other CS grad is fed with it.

I can't speak to any particular text for learning the language, since I mostly learned it through osmosis, but I can't stress enough how important it is to pick good tools to work with it. I would recommend Eclipse, and get to know it well (and rebind the Content Assist key to 'escape').

One thing that many people don't grok about Java is that programming it effectively is, essentially, computer-aided programming:
code:
New class.
private static final String FOOBAR = "BLAH";
private final Object someImmutableReference;
private Integer thisCanChange;

<ESC><*select the constructor from the autocomplete menu*><ENTER>
this.<ESC>s<*someImmutableReference*><ENTER> = <ESC><*someImmutableReference*><ENTER>
Eclipse warns that you're assigning itself to itself.<APPLE-1 or CTRL-1><ENTER>
Added as a parameter to the constructor.
Repeat for the other ones as you wish.
getS<ESC><ENTER>
Eclipse creates the getter for someImmutableReference.
setT<ESC><ENTER>
Eclipse can generate setters too.
<*right-click->Source->generate getters and setters*>
Eclipse can also do many at once.
<*right-click->Source->generate equals and hashCode*>
And make equals and hashcode methods
(important for the objects to be useful as keys in hashmaps for example)
<*right-click->Source->generate toString*>
And generate a toString for easier debugging.

End result: You only really had to declare the fields, but you now have a constructor, getters, setters, toString, and the object is ready to be put in a collection of some sort if necessary. You can even rename methods, variables, and entire classes and those changes will be effected globally throughout the project to anything else that refers to them.

Going back to what I said about books for teaching the language, I should amend that by saying that there are two books that are absolutely essential reading once you've got some footing with the language: Effective Java and Java Concurrency in Practice (the former being the most important IMO). These will give you clues on how to use Java well, but aren't exactly language books, per se. I think that Java itself is not terribly complex, but lends itself well to creating complexity (for better or worse) and hiding it behind abstracted interfaces.

Doctor w-rw-rw- fucked around with this message at 07:46 on May 9, 2012

pigdog
Apr 23, 2004

by Smythe

Doctor w-rw-rw- posted:

One thing that many people don't grok about Java is that programming it effectively is, essentially, computer-aided programming:

IDEA is even smarter than Eclipse when it comes to autocompleting and programming aides :)
http://blog.codeborne.com/2012/03/why-idea-is-better-than-eclipse.html

Doctor w-rw-rw-
Jun 24, 2008

pigdog posted:

IDEA is even smarter than Eclipse when it comes to autocompleting and programming aides :)
http://blog.codeborne.com/2012/03/why-idea-is-better-than-eclipse.html

Not significantly smarter for me to pass on official ADT support for Eclipse, is what it boils down to for me.

Doctor w-rw-rw- fucked around with this message at 08:34 on May 9, 2012

pigdog
Apr 23, 2004

by Smythe
Fair enough. IDEA does have some Android support even in the free edition, but I've no idea how it compares.

Blacknose
Jul 28, 2006

Meet frustration face to face
A point of view creates more waves
So lose some sleep and say you tried

pigdog posted:

IDEA is even smarter than Eclipse when it comes to autocompleting and programming aides :)
http://blog.codeborne.com/2012/03/why-idea-is-better-than-eclipse.html

I'm trying to give IDEA a go at the moment and while stuff like that is really nice in it I just can't seem to get it to 'feel' right, if that makes sense.

Honest Thief
Jan 11, 2009
I recently received a Java project from a colleague that implemented a class diagram's relations with sets. By that I mean something like A -> B -> C means A will have a Set<B> and B a Set<C>.
I'm wondering if there's a better implementation of it, because when I need to, say, get C from A I need to do 2 chained foreach, and I wonder if that's a good thing to do, since it could grow out of hand.

Honest Thief fucked around with this message at 10:31 on May 9, 2012

pigdog
Apr 23, 2004

by Smythe
With the caveat of not knowing the context, it doesn't look wrong at all. Are you sure you need to use foreach loops rather than say a HashSet, or something like someInstanceOfA.getSomeKindaB(someParameter).getSomeKindOfC(someOtherParameter)?

Doctor w-rw-rw-
Jun 24, 2008

Honest Thief posted:

I recently received a Java project from a colleague that implemented a class diagram's relations with sets. By that I mean something like A -> B -> C means A will have a Set<B> and B a Set<C>.
I'm wondering if there's a better implementation of it, because when I need to, say, get C from A I need to do 2 chained foreach, and I wonder if that's a good thing to do, since it could grow out of hand.
Sounds like an object graph rather than a hierarchy. If this is so then you'll probably need to add WeakReferences into the mix, or risk incredible memory problems. Can you explain more?

And with WeakReferences, it could definitely grow out of hand in verbosity and error-checking.

What kind of thing do you need to implement?

Honest Thief
Jan 11, 2009
The idea of the project was: we used USE and OCL expressions to define invariants and constraints for a certain model, then we were asked to implement those same constraints in Java; I should mention, the project is done and been delivered I simply had this nagging issue with it.

Anyway, the model in case was for a football championship, and we added some simple constraints and methods; for example to get the eldest of the players with OCL it was done simply by running:
"self.participation.team.age(self.birthDate)->max"

The issue came up in java, where I had to basically do something like

for(Participation p : this.participation)
for(Team t : p.team)
for(Player p:t.players)
p.age .....yadda yadda....

due to the how the model was implemented

Honest Thief fucked around with this message at 18:29 on May 9, 2012

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Blacknose posted:

I'm trying to give IDEA a go at the moment and while stuff like that is really nice in it I just can't seem to get it to 'feel' right, if that makes sense.

I was using Eclipse for about 4 years and recently switched to IDEA. I don't think I can go back to eclipse now, everything in IDEA is just way more intuitive.

Adbot
ADBOT LOVES YOU

Doctor w-rw-rw-
Jun 24, 2008

Honest Thief posted:

etc

for(Participation p : this.participation)
for(Team t : p.team)
for(Player p:t.players)
p.age .....yadda yadda....

etc

Well, seems reasonable to me, then.

fletcher posted:

I was using Eclipse for about 4 years and recently switched to IDEA. I don't think I can go back to eclipse now, everything in IDEA is just way more intuitive.
I've found the opposite, personally. Different (key)strokes for different folks, I guess

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply