|
Вы не можете заставить ее, но вы называете System.gc (), которая является "подсказку" для выполнения двигатель, который сейчас может быть хорошее время, чтобы запустить GC. Но сбор мусора с помощью этого метода не является гарантированно быть сделано немедленно.
|
|
Следующий wxample показывает, как создать код Java Source динамично и затем скомпилировать и запустить его.
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";
public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}
public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();
new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
// public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==-1);
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
|
|
Вы можете преобразовать десятичное в двоичное с использованием трех различных методов, как показано ниже:
int i = 42;
String hexstr = Integer.toString(i, 16);
or
String hexstr = Integer.toHexString(i);
or (with leading zeroes and uppercase)
public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}
|
|
|
В предоставлении услуг в области компьютерной науки, транспорта и исследование операций очереди буфера, где хранятся различные организации, такие как данные, объекты, лица, или события, и ждет, чтобы быть обработаны. Наиболее известные эксплуатацию очереди First-In-First-Out (FIFO) очереди процесс в очереди FIFO, первый элемент в очереди будет одним из первых, это равносильно тому, что всякий раз, когда элемент добавлены, все элементы, которые были добавлены до, должны быть устранены до начала нового элемента может быть вызван.
Существуют два основных операций, связанных с очередью: епдиеие и йедиеие. Добавляет означает добавление нового элемента в задней части а Dequeue очередь ссылается на удаление переднего элемента из очереди и возвращает его в пункт.
Следующий код показывает, как реализовать очередь с помощью связанных списков:
// ListQueue class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void enqueue( x ) --> Insert x
// Object getFront( ) --> Return least recently inserted item
// Object dequeue( ) --> Return and remove least recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// getFront or dequeue on empty queue
/**
* List-based implementation of the queue.
* @author Mark Allen Weiss
*/
public class ListQueue implements Queue {
/**
* Construct the queue.
*/
public ListQueue( ) {
front = back = null;
}
/**
* Test if the queue is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( ) {
return front == null;
}
/**
* Insert a new item into the queue.
* @param x the item to insert.
*/
public void enqueue( Object x ) {
if( isEmpty( ) ) // Make queue of one element
back = front = new ListNode( x );
else // Regular case
back = back.next = new ListNode( x );
}
/**
* Return and remove the least recently inserted item
* from the queue.
* @return the least recently inserted item in the queue.
* @throws UnderflowException if the queue is empty.
*/
public Object dequeue( ) {
if( isEmpty( ) )
throw new UnderflowException( "ListQueue dequeue" );
Object returnValue = front.element;
front = front.next;
return returnValue;
}
/**
* Get the least recently inserted item in the queue.
* Does not alter the queue.
* @return the least recently inserted item in the queue.
* @throws UnderflowException if the queue is empty.
*/
public Object getFront( ) {
if( isEmpty( ) )
throw new UnderflowException( "ListQueue getFront" );
return front.element;
}
/**
* Make the queue logically empty.
*/
public void makeEmpty( ) {
front = null;
back = null;
}
private ListNode front;
private ListNode back;
}
/**
* Exception class for access in empty containers
* such as stacks, queues, and priority queues.
* @author Mark Allen Weiss
*/
public class UnderflowException extends RuntimeException {
/**
* Construct this exception object.
* @param message the error message.
*/
public UnderflowException( String message ) {
super( message );
}
}
// Basic node stored in a linked list
// Note that this class is not accessible outside
// of package weiss.nonstandard
class ListNode {
// Constructors
public ListNode( Object theElement ) {
this( theElement, null );
}
public ListNode( Object theElement, ListNode n ) {
element = theElement;
next = n;
}
public Object element;
public ListNode next;
}
// Queue interface
//
// ******************PUBLIC OPERATIONS*********************
// void enqueue( x ) --> Insert x
// Object getFront( ) --> Return least recently inserted item
// Object dequeue( ) --> Return and remove least recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// getFront or dequeue on empty queue
/**
* Protocol for queues.
* @author Mark Allen Weiss
*/
public interface Queue {
/**
* Insert a new item into the queue.
* @param x the item to insert.
*/
void enqueue( Object x );
/**
* Get the least recently inserted item in the queue.
* Does not alter the queue.
* @return the least recently inserted item in the queue.
* @exception UnderflowException if the queue is empty.
*/
Object getFront( );
/**
* Return and remove the least recently inserted item
* from the queue.
* @return the least recently inserted item in the queue.
* @exception UnderflowException if the queue is empty.
*/
Object dequeue( );
/**
* Test if the queue is logically empty.
* @return true if empty, false otherwise.
*/
boolean isEmpty( );
/**
* Make the queue logically empty.
*/
void makeEmpty( );
}
|
|
|
Вы можете приостановить выполнение своей программы / Thread помощью сна () класса Thread класс. Следующем примере показано, как сделать это:
public class Wait {
public static void oneSec() {
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void manySec(long s) {
try {
Thread.currentThread().sleep(s * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestWait {
public static void main(String args[]) {
System.out.println("Wait one second");
Wait.oneSec();
System.out.println("Done\nWait five seconds");
Wait.manySec(5);
System.out.println("Done");
}
}
|
|
|
Этот образец кода необходим для полной и свободной памяти во время работы с консолью.
public class MemoryExp {
public static void main(String[] args) {
System.out.println("Total Memory"+Runtime.getRuntime().totalMemory());
System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());
}
}
|
|
|
подробно отображает всю информацию опцию при работе Java-приложений. Есть также несколько доступных расширений:
-verbose:class print information about each class loaded.
-verbose:gc Displays each garbage collection event.
-verbose:jni Report native methods used in application
|
|
Например переменная является переменной, которая связана с одним экземпляром класса. Создается каждый раз, когда экземпляр класса, система создает одну копию экземпляра переменных, относящихся к этому классу.
Например переменная delcared внутри класса, но не в рамках метода. Переменной, которая определена внутри класса и метод известен как локальную переменную.
Противоположность, например переменная является статической переменной, также называют переменной класса. Статическая переменная существует между экземплярами класса.
По умолчанию, все переменные, созданные как например переменные.
|
|
В компьютерной науке, стек временного абстрактных типов данных и их структуры, основанной на принципе Последний In First Out (LIFO). Стеки очень широко и широко используется в современных компьютерных системах, и, как правило, осуществляется через сочетание аппаратных и программных функций.
Следующий код показывает, как реализовать стек с помощью массивов:
// ArrayStack class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void push( x ) --> Insert x
// void pop( ) --> Remove most recently inserted item
// Object top( ) --> Return most recently inserted item
// Object topAndPop( ) --> Return and remove most recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// top, pop, or topAndPop on empty stack
/**
* Array-based implementation of the stack.
* @author Mark Allen Weiss
*/
public class ArrayStack implements Stack {
/**
* Construct the stack.
*/
public ArrayStack( ) {
theArray = new Object[ DEFAULT_CAPACITY ];
topOfStack = -1;
}
/**
* Test if the stack is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( ) {
return topOfStack == -1;
}
/**
* Make the stack logically empty.
*/
public void makeEmpty( ) {
topOfStack = -1;
}
/**
* Get the most recently inserted item in the stack.
* Does not alter the stack.
* @return the most recently inserted item in the stack.
* @throws UnderflowException if the stack is empty.
*/
public Object top( ) {
if( isEmpty( ) )
throw new UnderflowException( "ArrayStack top" );
return theArray[ topOfStack ];
}
/**
* Remove the most recently inserted item from the stack.
* @throws UnderflowException if the stack is empty.
*/
public void pop( ) {
if( isEmpty( ) )
throw new UnderflowException( "ArrayStack pop" );
topOfStack--;
}
/**
* Return and remove the most recently inserted item
* from the stack.
* @return the most recently inserted item in the stack.
* @throws Underflow if the stack is empty.
*/
public Object topAndPop( ) {
if( isEmpty( ) )
throw new UnderflowException( "ArrayStack topAndPop" );
return theArray[ topOfStack-- ];
}
/**
* Insert a new item into the stack.
* @param x the item to insert.
*/
public void push( Object x ) {
if( topOfStack + 1 == theArray.length )
doubleArray( );
theArray[ ++topOfStack ] = x;
}
/**
* Internal method to extend theArray.
*/
private void doubleArray( ) {
Object [ ] newArray;
newArray = new Object[ theArray.length * 2 ];
for( int i = 0; i < theArray.length; i++ )
newArray[ i ] = theArray[ i ];
theArray = newArray;
}
private Object [ ] theArray;
private int topOfStack;
private static final int DEFAULT_CAPACITY = 10;
}
/**
* Exception class for access in empty containers
* such as stacks, queues, and priority queues.
* @author Mark Allen Weiss
*/
public class UnderflowException extends RuntimeException {
/**
* Construct this exception object.
* @param message the error message.
*/
public UnderflowException( String message ) {
super( message );
}
}
// Stack interface
//
// ******************PUBLIC OPERATIONS*********************
// void push( x ) --> Insert x
// void pop( ) --> Remove most recently inserted item
// Object top( ) --> Return most recently inserted item
// Object topAndPop( ) --> Return and remove most recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// top, pop, or topAndPop on empty stack
/**
* Protocol for stacks.
* @author Mark Allen Weiss
*/
public interface Stack {
/**
* Insert a new item into the stack.
* @param x the item to insert.
*/
void push( Object x );
/**
* Remove the most recently inserted item from the stack.
* @exception UnderflowException if the stack is empty.
*/
void pop( );
/**
* Get the most recently inserted item in the stack.
* Does not alter the stack.
* @return the most recently inserted item in the stack.
* @exception UnderflowException if the stack is empty.
*/
Object top( );
/**
* Return and remove the most recently inserted item
* from the stack.
* @return the most recently inserted item in the stack.
* @exception UnderflowException if the stack is empty.
*/
Object topAndPop( );
/**
* Test if the stack is logically empty.
* @return true if empty, false otherwise.
*/
boolean isEmpty( );
/**
* Make the stack logically empty.
*/
void makeEmpty( );
}
|
|
|
Java сделать цикл похож на Java в то время как петля, кроме того, что происходит в то время испытаний в конце цикла. Это означает, что цикл всегда выполняется по крайней мере один раз.
Синтаксис делать петлю в Java это:
do {
statement(s)
} while (expression);
|
Вот Java сделать цикл, который печатает номер 1 - даже если проверка не прошла.
int loopvar = 1; // Declare and initialize the loop counter
do {
System.out.println(loopvar); // Print the variable
loopvar = loopvar + 1; // Increment the loop counter
} while (loopvar >= 10); // Test and loop
|
|