KilianZoll
KilianZoll

Reputation: 3

Looking for a way to make a simple database or list in Java (More advanced than HashMap, easier than JDBC)

I'm pretty new to Java, and I'm writing a program that needs to store:

  1. Customer data
  2. Product data

In separate lists.

I've tried with HashMap, hashtable as well as ArrayList of old, but it gets really messy when I've got to store, for example, the product name (Str), selling price (int), buying price (int), a description (Str) and a product type (boolean). I've been looking at JDBC, but it looks really complicated to set up, but I'll try either that or java.sql if there's no other way.

What I'm looking for is a kind of HashMap that allows more "rows".

Upvotes: 0

Views: 93

Answers (2)

Andrew Spencer
Andrew Spencer

Reputation: 16504

First you need to decide whether you really need a database. If you want a database and you don't want the trouble of writing all the JDBC code, I advise an ORM like Hibernate or EclipseLink - but be warned that they are leaky abstractions, and if you get beyond the simplest use cases, you'll need to know everything you'd have needed to know about JDBC, plus a whole bunch of stuff specific to the ORM framework.

If you want to stick with in-memory data structures, then look at Google's Guava Collections which have a number of data structures more sophisticated than plain maps. But what will you do when you need to persist them? Serialize to disk? That in itself is (potentially) a whole swimming pool of pain.

Moral of the story: persistence is hard work.

Upvotes: 2

kgiannakakis
kgiannakakis

Reputation: 104198

Create a class that will model the entity you need to store:

public class Entity {
  private String name;
  private int id;
  private BigDecimal price;

  // Add getters and setters
}

Then you can use any Collection to store them:

List<Entity> entities = new ArrayList<Entity>();

You may also want to consider an ORM solution. This will make database handling a lot easier.

Upvotes: 2

Related Questions