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
1337JiveTurkey
Feb 17, 2005

Trifling Fox posted:

Retarded CS major here.

Is there anyway to use the JTextField class and Scanner class together? I'm looking at the API and I can't find a method to use here.

Sorry for such a long post, but just knowing there isn't a way is only half the story. JTextField and other GUI objects work under a completely different principle than you're used to from writing apps that use Scanner and System.in. The way you're used to is you write a program that starts from the beginning of main() and you trace the flow of control all the way to the end. If the user hasn't entered a line on the console, the Scanner blocks (waits) until something happens and the flow of control stops.

Intuitively it feels like we should be able to make a program with a GUI which acts the same way but then the question arises: If I'm waiting for one thing but the user does something else, how can I react? There are three solutions: The first was making a seperate flow of control (thread) for everything. It sounds good in theory, but what happens if you press on one button before another's done processing? Very bad things, that's what. The only use of that solution was BeOS which had a reputation for being quick, responsive and buggy as gently caress.

The second option is to have one flow of control which doesn't wait for something to happen, it just loops over everything in the GUI to see if something changed (polling) but never waits for anything to happen. Embedded computers like in cars use this because it doesn't take a lot of elaborate software or specialized hardware to make it work.

Finally, we can have one flow of control which waits for anything to happen at all, figures out what to do based on what happened, and then waits for the next event. It sounds painful to write code which can handle anything that a user can do in a GUI considering that there's gotta be hundreds of possibilities. Most modern OSes as well as Swing use this method, but they don't force you to write one big loop that does it all.

Instead, they have what's called the event dispatch loop or event dispatch thread. You create event listeners and register them with this loop. Event listeners have code that you want performed when some event happens, like when the user presses enter on a JTextField.

code:
public class ExampleAction extends java.awt.event.ActionListener {
	public void actionPerformed(java.awt.event.ActionEvent e) {
		// This only works when this event is registered on a JTextField
		JTextField field = (JTextField) e.getSource();
		// We get the text the user entered from the field
		String input = field.getText();
		// And then we empty the field out for the next time
		field.setText("");
		// Here's where you do what you normally would after myScanner.nextLine()
		// Once that's done, leaving this method is like calling myScanner.nextLine()
	}
}
Here's where it gets confusing to new programmers: You never actually call actionPerformed() and you never actually create an ActionEvent to send to it. Instead what happens is when the user presses enter on the registered JTextField the OS tells the event dispatch thread which then creates an ActionEvent and calls your registered ExampleAction with it. When you're done, the event dispatch thread waits for the next event. The flow of control as you're used to is completely upside down since instead of your code doing the looping and calling the scanner code, the Swing code is doing the looping and calling your code. Unfortunately this means that there's no good way to mix the two since they're totally and fundamentally incompatible.

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

If you create a HttpURLConnection from a URL (cast the regular URLConnection), that's a bit more high level and has convenience methods for HTTP-specific functionality.

1337JiveTurkey
Feb 17, 2005

OK. The easiest way to do this is to break it up into two problems. First you need to distinguish where the start and end of a parseable command is. If the user is pressing enter after each command, then you really want to just get the next line rather than searching for tokens. There are several ways to do this, but one of the simpler ways is to just take System.in and then wrap it in a InputStreamReader and then a BufferedReader like so:

code:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in);
String nextLine = reader.readLine();
while (nextLine != null) {
  // The split command splits the line into individual tokens
  String[] tokens = nextLine.split("\\s+");
}
After that as the code shows, you can split the individual line up into parts and then you have the number of tokens beforehand and you can look at the first token to tell how many tokens you should expect.

1337JiveTurkey
Feb 17, 2005

That can be painfully slow if the number of items increases much beyond where it is. If you're looking for a shuffled list of numbers, then this should be what you need:
code:
List<Integer> shuffled = new ArrayList<Integer>();
for (int i = 0; i < length; i++) {
  shuffled.add(i+1);
}
Collections.shuffle(shuffled);

1337JiveTurkey
Feb 17, 2005

JBoss uses the Log4J logging framework. You can find the configuration file for it in the config directory of your server. If you're just looking for calls to System.out, just make a subclass of PrintStream that wraps the real/current System.out and sends everything to it instead. Remember: System.out isn't final so you can replace it with whatever you want. You can set a breakpoint there or you can just create a Throwable, getStackTrace() it and get the second element. That's got the class, method, file name and line number (if you compiled those in) for whatever printed to System.out.

edit: If you find the Log4J config file, you can filter specific packages IIRC so you can at least shut those ones that constantly spam poo poo in debug mode up.

1337JiveTurkey
Feb 17, 2005

You've got the original list, an argument that's a copy of the original list, and an argument that's an iterator on the original list. The iterator is the only one you're currently using, but you actually don't want to pass it as a parameter.

The simplest method for getting all of the possible anagrams is to start with the collection of letters and a blank string for the anagram so far and then go through all the words in the dictionary. If it doesn't fit, skip it. If it fits, then append it to the anagram so far. If the fit was exact, print it out and continue. Otherwise recurse with the remaining letters and the new anagram. It'll obviously be slow but there are a few techniques for speeding it up if you need them.

1337JiveTurkey
Feb 17, 2005

Warblade posted:

This question is kind of language agnostic, but I'm dealing with Java so maybe there's some kind of Java convention for doing this. Say you write a class that accepts some kind of listener. At some point you'll be iterating through all of your listeners to notify them that something significant happened. Maybe the method call is listener.sendEvent().

Is there some kind of best practice, or convention for what the sender and receiver should and shouldn't do?

I guess it would be good defensive programming to spawn a worker thread that actually calls listener.sendEvent(). But, as a receiver, should you also strive not to do things like sleeping for some indeterminate amount of time, or is it simply up to the sender to protect itself against that kind of situation?

All event listeners in Java should derive from the java.util.EventListener interface, and all objects giving the specifics of a certain event should use the java.util.EventObject. Those are more markers than anything else, but they're what everyone expects for typing purposes. The javax.swing.event.EventListenerList can store listeners of multiple different types in one array and returns an iterator of only the type that you want when you pass it the corresponding class object. Normally that's wrapped so that there's a public addFooListener() method which adds a listener, a public removeFooListener() which removes the given listener, a getFooListeners() which returns an array of the registered listeners, and one or more protected fireFoo() methods corresponding to the events which the listeners can receive. These events should normally create a new object of the correct type, initialize it and then send it to all of the listeners. As a rule, the sender owns the event and the receivers shouldn't change it at all but this is by convention so the sender shouldn't create duplicates of any data it sends.

Listeners should generally be quick and return immediately. Quick in GUI terms is actually a surprisingly long period of time, but never block on the event loop. You know when Windows says a program has stopped responding? Dollars to donuts some genius went and did that because no events deposited in the queue by the OS in the last five seconds have been retired. There are methods for only attempting to grab a resource which will just return false if they fail and can be used, but generally anything that needs to wait for something should be spawned off into a separate worker thread while everything else can safely be done in the main event loop.

Two things to pay particular attention for are event loops and cascades where events trigger other events which can lead to a non-local infinite loop or just horrible performance as something gets triggered way too many times. I find that this often happens when there's both a 'real' model and another model which exists solely for the view and the controller and the programmer attempts to synchronize the two through events. Either use the default models to store the real data or wrap the real data structures in the appropriate interfaces in that case.

Finally watch out for keeping references in listeners to other parts of the GUI. It's better to send everything through the associated EventObject so that there aren't any spurious references keeping things from being garbage collected.

1337JiveTurkey
Feb 17, 2005

A using or with block would go a long ways to making that stuff sane. On the plus side it does look like at least the null pointer checks are going to be less painful in Java 7 since they're certain at this point that it'll have the .? short-circuiting dereference operator. istream.?close() would call the method only if the stream isn't null. They'll also add another assignment operator foo ?= bar which assigns bar to foo iff foo is null. Also on the topic of closing streams, they've got some neat new annotations for IDEs that can be added to parameters in method signatures to tell whether stream arguments will be closed at the end of the method call or not.

1337JiveTurkey
Feb 17, 2005

The lack of unsigned numbers don't bother me too much at least as far as work goes. There's two things which unsigned numbers provide: An implicit lower bound on possible values and twice the number of possible positive values. The implicit lower bound is nice, but it's no substitute for proper bounds checking every input.

The extra positive range is pretty much illusory: If n bits isn't enough n + 1 bits won't be enough in practice. Any company can grow to or churn through 256 employees if they can do 128, and ~2 billion employees isn't any less laughable than ~4 billion. Y2038 fix proposals aren't talking about just using an unsigned number because even if it pushes things back until after almost everyone is dead, 64 bit just isn't that big of a deal these days. When I get an unsigned number smaller than 32 bits in some imported data, treating it as an int for internal calculations doesn't hurt anything as long as I remember its 'real' range for when it counts, such as writing it back out.

Performing arithmetic on numbers that use the extra range is spotty since beyond multiplication possibly causing overflow, now addition and subtraction can as well. Since Java continues on the C tradition of not trapping them and letting the programmer sort it out, it's a whole extra can of worms dumped on top of everything else.

That said, I'm extending an emulator someone wrote for the MIPS architecture to some other ones for fun and it seems like I'm doing a lot of ((long) foo) & 0x00000000FFFFFFFF. It's tedious at points but at least most operations are identical in practice so I can just add, shift or multiply and not give a gently caress since the only difference is the interpretation of the result.

1337JiveTurkey
Feb 17, 2005

As far as I know using a date which could even remotely be construed as valid to stand in as an invalid date or null date is never considered a good practice. new Date(Long.MIN_VALUE) would be several hundred MYA. In this case just using null would do the exact same thing you're expecting.

1337JiveTurkey
Feb 17, 2005

Honestly unless your output file is going to be absolutely MASSIVE, stick them into a LinkedHashSet<String> and just iterate through that when the input file is empty.

1337JiveTurkey
Feb 17, 2005

Clock Explosion posted:

Out of curiousity, why do you recommend a LinkedHashSet rather than some other data structure?

LinkedHashSet enforces uniqueness while preserving the insertion order. It gives the exact same effect as searching through the output file every single iteration without the cost of O(n^2) IO operations.

edit: Instead, there'd be O(n) IO operations and the hashset accesses won't even show up on a profiler.

1337JiveTurkey
Feb 17, 2005

HFX posted:

Yep. A set enforces uniqueness. That is why I used it. The iterator you get from it is guaranteed to be in order or insertion. See my code.

Er, why bother with the removeDuplicatedLines() method then?

1337JiveTurkey
Feb 17, 2005

StickFigs posted:

I'm having a little trouble understanding your code, right now I'm trying to figure out how you output the populated LinkedHashSet to the .txt file. Looking at it now I see:

code:
for(String outputLine : inputFile1Contents) {
			writer.println(outputLine);
		}
I don't understand anything about that snippet of code except for just "writer.println(outputLine);", but I don't understand how outputLine gets a value or anything. (I guess it's probably because I don't understand the ":" usage there since it doesn't look like an if-else statement.)

That's foreach. It's a for loop which will go through every single item in a set, list, array or anything else that implements Iterator<T>. It automatically sets outputLine every time it loops through and terminates when it runs out of items.

1337JiveTurkey
Feb 17, 2005

For the purposes of making a file uploader, a JNLP-launched applet would work. JNLP allows a slightly larger set of permissions than plain applets such as to create a file open dialog.

https://jdk6.dev.java.net/plugin2/jnlp/

1337JiveTurkey
Feb 17, 2005

krooj posted:

Question - JavaFX is piqued my interest as a cleaner alternative to the poo poo-show that is AJAX, but I am wondering what the difference is between JavaFX and a regular ol' Applet. Any huge diff?

It's got a more declarative language for making UIs and it's supposed to be multiplatform as well. As long as it doesn't depend on any libraries that wouldn't be available on a mobile platform, it'll work on that as well. It also supports WebStart so that it can be used as a standalone application by putting a JNLP file on the server.

1337JiveTurkey
Feb 17, 2005

Here's a few possible things to look at in the base API:

  • The java.io, java.util.zip, java.net and related basic IO libraries are very generally applicable.
  • RMI builds on the basic IO libraries to provide an easy way to write code distributed across many computers.
  • The java.text and java.regex text processing libraries can drastically simplify many things you've used lots of if-then statements for.
  • The Swing UI libraries are very powerful and a considerable upgrade from the command line.
  • JDBC is the standard way to connect to databases. You'd need a database for this, but there are many good ones out there.

I'd suggest avoiding anything related to Java Enterprise Edition, EJB or the like until you're thoroughly acquainted with the basics. There's also a huge number of open source projects to look through. Robocode in particular is a good choice for beginner programmers.

1337JiveTurkey
Feb 17, 2005

rhag posted:

To get what you want, you'll need to create a custom scrollable component (extents JPanel probably).
You have a nice tutorial here: http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html#scrollable

That's one option. The other is to just drop a JPanel in there and put all of the components inside of that.

1337JiveTurkey
Feb 17, 2005

Fehler posted:

I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code.

So basically I'm looking for something like a DLL equivalent in Java. I think I read about something like this once, but I'm unsure on the details. Is there even such a thing in Java? How hard would it be to implement? What are some good starting points?

Every class file is effectively a dll. A classloader like a URLClassLoader is used to load the class from a Jar file, then the class can be instantiated through reflection and used normally.

1337JiveTurkey
Feb 17, 2005

It's possible to make those <T extends Enum> into <T extends Enum & CostTypeInterface>. (Syntax might be off) The interface can have whatever methods you want for the user to implement, allowing for some specialized behavior.

1337JiveTurkey
Feb 17, 2005

Relative paths are determined from the working directory where the java command itself is run. For IDEs this usually isn't inside of the source path. NetBeans and IntelliJ both use the project root directory, so try there. If you've got the file in the same directory as the .class file and you only need to read from it, it can be reached using ClassWork7.class.getResourceAsStream("tas.txt").

1337JiveTurkey
Feb 17, 2005

Do you know the actual type of the array where you're calling it? The Collection.toArray() method takes an array of the type that you want and uses reflection to make a bigger one if it's not large enough.

code:
Collection<String> foo = new ArrayList<String>();
String[] bar = foo.toArray(new String[foo.size()]);
Since Java generics don't retain that information at runtime and arrays need an actual type to construct from, this means that a type needs to be supplied at the time of construction. While the Collection.toArray() method is one example the static method ServiceLoader.load() takes a Class<T> as its argument (usually an interface) and returns a ServiceLoader<T>.

Of course if you can't change it, things get messy. One possibility (haven't tested it but it should work) is to figure out the type based on the elements of the iterator. Keep in mind that this is mostly from memory written in an IDE called 'Firefox'.

code:
// This will be a list of all the possible classes the array can be
List<Class> classes = null;
Class<T> survivor = null;
for (T t : bar) {
  if (classes == null) {
    // Adding the classes on the first pass is the same as removing
    // everything else from the universal set
    classes = Arrays.asList(t.getClass().getClasses())
  }
  else {
    // Rest of the iterations remove classes from the initial one
    classes.retainAll(Arrays.asList(t.getClass().getClasses()));
  }
}
if (classes.size() == 1) {
  survivor = (Class<T>) classes.get(1);
}
else {
  // Now to trim things down a bit by removing the boring ones
  List<Class> remaining = new ArrayList<Class>(classes);
  for (Iterator<Class> it = remaining.iterator(); it.hasNext();) {
    Class candidate = it.getNext()
    for (Class clazz : classes) {
      if (candidate == Object.class ||
          candidate != clazz &&
          candidate.isAssignableFrom(clazz)) {
        it.remove();
        break;
      }
    }
  }
  if (remaining.size == 1) {
    survivor = (Class<T>) remaining.get(0);
  }
  else {
    survivor = (Class<T>) remaining.get(new Random().nextInt(remaining.size));
  }
}
// Use reflection to generate an instance of the actual class
T[] retVal = (T[]) Array.instanceOf(survivor, bar.size());

1337JiveTurkey
Feb 17, 2005

Fly posted:

Could that be a byte-order mark (BOM)? http://unicode.org/faq/utf_bom.html#BOM

It's the length of the encoded string in bytes. The actual string encoding isn't exactly UTF-8, but instead a modified version which preserves surrogate pairs and null characters without leaving any embedded nulls in the encoded bytes. That method is more for quick and efficient byte-for-byte precision in the deserialized data than it is for byte-for-byte precision in the serialized form.

1337JiveTurkey
Feb 17, 2005

Install a custom SecurityManager just before the code is called such that checkExit() throws a SecurityException every time. Then in the finally block remove the manager so that you can actually exit normally. If you reach the catch block with a SecurityException, some brilliant soul decided to handle an error by calling Runtime.exit() or Runtime.halt().

1337JiveTurkey
Feb 17, 2005

Rsugar posted:

I'm making a tile-based game, and I'm a little confused on this:
I have an array for my map, and I have a tile system. A Tile has numerous values, like pollution, power, type, etc. How do I tell the system what part of the array is what kind of tile, and what the values in that specific tile in that part of the array are?

You can just make a Tile object which has the appropriate getters and setters for the basic attributes. Tile-specific behavior can be handled through subclassing. Then just stick them into your array and just look it up using the coordinates when you need them.

edit: Are you having trouble with array lookups?

1337JiveTurkey
Feb 17, 2005

timecircuits posted:

I have an interview on Thursday for an internship wherein I would be writing Java.

Now, they're looking for somebody at a junior level so they probably don't expect me to have much more experience than an undergraduate algorithms class, basic principles of software development, and data structures -- all of which I'm totally confident in and I have no worries about my ability to interview confidently based on them.

On the other hand, my knowledge of Java goes about as far as implementing a binary search tree. 99.98% of my programming experience is in C++, which I'm definitely intermediate level with.

Is there some "Java for retards who happen to know C++ pretty well" website? I just need something I can read in an afternoon that tells me "X feature in Java is really Y feature in C++" so if I get Java-specific questions like "when would you use a java beans AWT noun noun noun" I can answer them without looking like a horrible moron.

Java is significantly different from C++ in how it's used so it's hard to just give a 1:1 mapping beyond libraries like SAX or OpenGL/JOGL. The official tutorials keep the basic language syntax to one section of one tutorial so you can just skip the stuff on basic flow control. You'll probably want to understand how Java handles exceptions differently as well as how it handles inheritance but those are both less complex than C++. The tutorials also cover a lot of the basic libraries that you'll want to know. Focus on having a solid understanding of the basics and don't worry about the more complex APIs. There's always the risk that you'll run into some insane interviewer who considers knowing how to diagnose bizarre classpath issues running WAS 6.1 on Solaris to be fair game but you can't plan for every contingency. On the other hand it's much more likely that they'll want someone who understands the difference between a List<String>, a LinkedList<String> and an ArrayList<String> and which can be used in place of which.

1337JiveTurkey
Feb 17, 2005

MEAT TREAT posted:

I was going to say that I've never found a use for a LinkedList over an ArrayList, but then I remembered that it implements the queue and deque interfaces.

It's also good for data structures 1 homework where your professor thinks your name is Josh Bloch.

1337JiveTurkey
Feb 17, 2005

ynef posted:

In math, you'd probably get away with ceil(log2(given_number)), but Java doesn't have a general logarithm function like that (just the natural logarithm). You'd have to use the Change of Base theorem to compensate.

ceil(log2 n) = 32 - Integer.numberOfLeadingZeroes (n - 1) for all positive n.

1337JiveTurkey
Feb 17, 2005

This code is under the presumption that you're looking for there to be many possible implementations of the abstract class but want only one at runtime. Using System.getProperty() isn't necessary but fits with established practice in the libraries. In order to make this work, you'll also need to make sure that you've got a META-INF/services directory in the JAR file with the children of the Connection class listed.

code:
public static synchronized Connection getInstance() throws ConnectionException {
	if (uniqueInstance != null)
		return uniqueInstance;
	String connectionType = System.getProperty("Connection.Type");
	for (Connection connection : ServiceLoader.load(Connection.class)) {
		if (connectionType.equals(connection.getConnectionType()) {
			uniqueInstance = connection;
			return uniqueInstance;
		}
	}
	throw new IllegalStateException("No Connection has type " + connectionType);
}

1337JiveTurkey
Feb 17, 2005

amr posted:

I'm building the GUI for a program I'm working on and I've hit a bit of a problem.

My GUI is arranged in the following way: a 'main' JFrame that is always open, a JTree in the JFrame (on the left), and a large JPanel taking up the rest of the JFrame. I'm swapping panels in and out of that JPanel, depending on what the user wants to do.

The problem I have is I'm not sure how to assemble my JTree and for it to load new instances of my the JPanels. Any ideas?

Edit: I can do the actual swapping, I've written a setPanel() method for the main window. I basically need to call setPanel(new NameOfNewPanel()); when a user clicks on an item in the JTree.

CardLayout on the right hand side to swap things, then put a TreeSelectionListener on the tree to be informed whenever the user picks something different. Usually you'd make or extend your own tree model to store the information about the editor that should be shown for that tree node.

1337JiveTurkey
Feb 17, 2005

amr posted:

That's what I'm doing currently. CardLayout to swap the panels, and extending my own tree, the problem is I'm not sure how to store nodes in the JTree and then how I should load the correct panel. Currently I've got a big switch statement and I'm swapping based on the node's toString() (not the best idea, I know, that's what I'm wanting to change it)

Swing is MVC-oriented, so the idea is that your data should either implement the TreeModel or TreeNode interfaces or have that as a front end that ultimately manipulates them. Then it's not really a question of how you store the nodes because then the JTree is just a window (the View) onto your Model. The tree then by default displays the toString() of the nodes themselves and you can have all the data you need inside of the nodes. To pick what to display there's a few ways.

The most straightforward method of just having a method that gets the panel itself on the node has the problem that it sticks a dependency on your View in the Model when generally it should always be in the other direction. Using a map of node classes to right hand panels could also work. The selection listener would then get the selected node and look up its class to find the correct right hand panel, then pass the node to the panel in some initialize method. That can be made as simple or as complex as you like.

1337JiveTurkey
Feb 17, 2005

amr posted:

Thanks for your advice, although some of that went way over my head :P This is my first time actually doing a proper user interface for my program. I'm still not quite sure how to do it. I was thinking of trying to use reflection or having a static getInstance() method. Do you know of any material I can read so I know what I'm doing? Cheers

These two articles give a 10,000 foot overview of Swing and MVC:
http://en.wikipedia.org/wiki/Swing_(Java)
http://en.wikipedia.org/wiki/Model%96view%96controller

Here's the standard tutorial which covers how to use Swing in depth:
http://java.sun.com/docs/books/tutorial/uiswing/

To answer your question, it really depends on what your requirements are. For the one-off utilities that I've worked on, just slapping a getPanel() method on the node itself is often perfectly adequate even if it tightly couples some aspects of the program. For the flagship application I work on, it's a full-fledged subsystem with dozens of pluggable editors available for various combinations of nodes along with stuff like dynamic per-seat licensing. If I were to remove the huge amount of legacy cruft on it and pare it down to its core, that'd be basically the controller for the right hand panel asking all of the editors "can you edit this set of nodes?" and then adding a tab for each one that returns true. It works well with plugins and is pretty much instantaneous even with well over 100 different possible tabs since they're just looking at the number of nodes as well as their class.

1337JiveTurkey
Feb 17, 2005

ynef posted:

Well, you can always over-engineer it by using a ScheduledExecutorService if you want, but what you had should work too.

I'd say that 90% of my stress at work is from people ignoring established solutions to complex problems in favor of their own hacked together solutions that mistake their inability to understand the entirety of the problem for an eye for elegance. It's one loving object with a one argument constructor and a method that takes the exact same Runnable he'd have to write otherwise plus however long he wants to wait. It doesn't get any loving simpler than:

code:
Runnable periodicTask = new Runnable(){/* stuff */} 
// One thread in the pool since it's just running this task
ScheduledExecutorService myService = new ScheduledThreadPoolExecutor(1);
// No initial delay, 3 hours from task start to start
myService.scheduleAtFixedRate(periodicTask, 0, 3, TimeUnit.HOURS);
I tossed in a couple of comments to hopefully make the purely numeric method arguments as obvious as humanly possible for someone who's never touched the API before. It's far easier for someone new to understand than the alternative while still allowing for a great deal of future flexibility.

Long story short: Use java.util.concurrent unless you're using Swing or JEE in which case consider the more specialized variants that they provide.

1337JiveTurkey
Feb 17, 2005

Arguments to a method can be declared final in the implementation although it's not allowed in an abstract method. This simply indicates that the method will not change the values passed in even if pass by value semantics are enforced on all method calls normally. This is required if the values are to be accessible from within a local class defined inside the method. Otherwise it's merely a helpful indicator for the compiler when optimizing code and a way to ensure that the value isn't changed inadvertently.

1337JiveTurkey
Feb 17, 2005

Yes. Streams that wrap other streams are supposed to close the underlying stream when they are closed unless there's a reason for them not to, in which case the calling code probably isn't supposed to close the underlying stream in the first place like the output stream for a zip file entry.

1337JiveTurkey
Feb 17, 2005

If you call a program from the command line, normally you can include stuff beyond just the program name. For instance a program that copies a file would take the existing file and the name of the file you want to copy it to. In that case you would expect for the existing file name to be in args[0] and the new file name to be in args[1]. This is similar to how it's done in other languages like C, although in C the first parameter is always the name of the program being called (useful in some circumstances).

1337JiveTurkey
Feb 17, 2005

Jabor posted:

Is that actually the spec, or just an implementation detail?

Spec. The JVM integer math operations act on 32-bit numbers or 64-bit numbers. Stuff gets sign extended when pushed on the stack and truncated when popped IIRC.

1337JiveTurkey
Feb 17, 2005

Jabor posted:

Right, so the spec is that the result is the same as if the math was performed on a 32-bit sign-extended version.

But there's no requirement that a conforming implementation actually do this, is there?

Due to the rules of mathematics they act the same. Try it using 2 and 4 digit numbers and base 10 arithmetic rather than 8 bit or 32 bit numbers and you'll see that when you chop the first 2 digits off a 4 digit number it acts identically to the 2 digit number.

Specs in general only define behavior, so as long as an implementation behaves identically, it's perfectly fine. You could write a stackless C implementation that uses garbage collected activation records instead and it'd be perfectly legal, if a bit perverse. Most RISC processors just have one add instruction since it acts identically for all widths both as 2's complement as well as unsigned so they have to implement it in that manner. An IA-32 processor could treat a push of a byte onto the stack as loading into one of the byte-sized registers but you wouldn't be able to tell the difference.

1337JiveTurkey
Feb 17, 2005

Scala's probably going to get more use out of the MethodHandles as a way to handle eta expansion without generating new anonymous classes. That's also the direction that Java 8 looks to be going with lambda definitions with some way to make a single MethodHandle with a given MethodType impersonate an interface or abstract class with a single abstract method of the same MethodType.

Also, the escape analysis being enabled by default in Java 7 (and I think Java 1.6u23 and up as well) will probably have a bigger impact on Scala programs. Being able to stack allocate millions of tiny objects with short lifespans turns them from cheap into effectively free. This has caused some (highly contrived) microbenchmarks to run several times faster in tests but the average Scala program's still going to benefit somewhat since it does allocate a lot of the aforementioned tiny objects with short lifespans.

Adbot
ADBOT LOVES YOU

1337JiveTurkey
Feb 17, 2005

To take a somewhat fundamentalist position, the only place that you should really be referring to the implementation class outside of its implementation should be the constructor. If that's the case, then the interface shouldn't have its name mangled.

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